6

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

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

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

    http://localhost:22297/api/values?someinvalidparameter=10

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

4

2 回答 2

8

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

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);
            }
        }
    }
}
于 2013-01-30T23:34:20.957 回答
2

为了使其能够很好地使用开箱即用的验证支持,我创建了自己的操作选择器,它可以将 URI 参数绑定到复杂类型的对象而不会重复。

因此,您可以使用此操作选择器执行以下操作:

public class CarsByCategoryRequestCommand {

    public int CategoryId { get; set; }
    public int Page { get; set; }

    [Range(1, 50)]
    public int Take { get; set; }
}

public class CarsByColorRequestCommand {

    public int ColorId { get; set; }
    public int Page { get; set; }

    [Range(1, 50)]
    public int Take { get; set; }
}

[InvalidModelStateFilter]
public class CarsController : ApiController {

    public string[] GetCarsByCategoryId(
        [FromUri]CarsByCategoryRequestCommand cmd) {

        return new[] { 
            "Car 1",
            "Car 2",
            "Car 3"
        };
    }

    public string[] GetCarsByColorId(
        [FromUri]CarsByColorRequestCommand cmd) {

        return new[] { 
            "Car 1",
            "Car 2"
        };
    }
}

然后,您可以注册一个操作过滤器来验证用户输入以终止请求并返回“400 Bad Request”响应以及验证错误消息:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class InvalidModelStateFilterAttribute : ActionFilterAttribute {

    public override void OnActionExecuting(HttpActionContext actionContext) {

        if (!actionContext.ModelState.IsValid) {

            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}

查看以下帖子以获取有关此操作选择器以及如何获取它的更多信息:

于 2013-01-31T08:32:03.520 回答