ASP.NET Web API避免查询字符串中的无效参数

jro*_*ies 5 filter query-string asp.net-web-api

给定以下Web API控制器操作:

    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
Run Code Online (Sandbox Code Playgroud)

即使查询字符串中的参数不存在,执行以下请求也不会失败:

    http://localhost:22297/api/values?someinvalidparameter=10
Run Code Online (Sandbox Code Playgroud)

有没有办法确保查询字符串中的所有参数都是被调用操作的有效参数?

Rag*_*nti 6

您可以编写一个操作过滤器,验证操作参数中是否存在所有查询参数,如果不存在则抛出.

using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace My.Namespace.Filters
{
    /// <summary>
    /// Action filter that checks that parameters passed in the query string
    /// are only those that we specified in methods signatures.
    /// Otherwise returns 404 Bad Request.
    /// </summary>
    public class ValidateQueryParametersAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// This method runs before every WS invocation
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            //check that client does not use any invalid parameter
            //but just those that are required by WS methods
            var parameters = actionContext.ActionDescriptor.GetParameters();
            var queryParameters = actionContext.Request.GetQueryNameValuePairs();

            if (queryParameters.Select(kvp => kvp.Key).Any(queryParameter => !parameters.Any(p => p.ParameterName == queryParameter)))
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)