鉴于以下Web API控制器操作:
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
即使查询字符串中的参数不存在,执行以下请求也不会失败:
http://localhost:22297/api/values?someinvalidparameter=10
有没有办法确保查询字符串中的所有参数都是被调用操作的有效参数?
答案 0 :(得分: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);
}
}
}
}
答案 1 :(得分: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);
}
}
}
查看以下帖子,了解有关此操作选择器的更多信息以及如何获取它: