我想为我的 Web API 创建一个全局 valdiation 属性。所以我按照教程结束了以下属性:
public class ValidationActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid)
{
return;
}
var errors = new List<KeyValuePair<string, string>>();
foreach (var key in actionContext.ModelState.Keys.Where(key =>
actionContext.ModelState[key].Errors.Any()))
{
errors.AddRange(actionContext.ModelState[key].Errors
.Select(er => new KeyValuePair<string, string>(key, er.ErrorMessage)));
}
actionContext.Response =
actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors);
}
}
然后我把它添加到 Global.asax 中的全局健身者中:
configuration.Filters.Add(new ValidationActionFilter());
它适用于我的大多数操作,但不适用于具有可选和可为空的请求参数的操作。
例如:
我创建了一个路由:
routes.MapHttpRoute(
name: "Optional parameters route",
routeTemplate: "api/{controller}",
defaults: new { skip = UrlParameter.Optional, take = UrlParameter.Optional });
还有我ProductsController
中的一个动作:
public HttpResponseMessage GetAllProducts(int? skip, int? take)
{
var products = this._productService.GetProducts(skip, take, MaxTake);
return this.Request.CreateResponse(HttpStatusCode.OK, this._backwardMapper.Map(products));
}
现在,当我请求此 url: http://locahost/api/products
我收到包含 403 状态代码和以下内容的响应:
[
{
"Key": "skip.Nullable`1",
"Value": "A value is required but was not present in the request."
},
{
"Key": "take.Nullable`1",
"Value": "A value is required but was not present in the request."
}
]
我相信这不应该显示为验证错误,因为这些参数既是可选的又可空的。
有没有人遇到过这个问题并找到了解决方案?
还希望避免/禁止在GET请求中对基元类型进行模型验证。
public class ModelValidationFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid && actionContext.Request.Method != HttpMethod.Get)
{ ...
之间搞砸了代码,你应该使用Web API中的RouteParameter而不是MVC中的UrlParameter
。routes.MapHttpRoute(
name: "Optional parameters route",
routeTemplate: "api/{controller}",
defaults: new { skip = RouteParameter.Optional, take = RouteParameter.Optional }
);
但:
路由跳过和获取的默认参数对路由机制没有任何作用,因为您只是在查询字符串中使用它们,而不是在路由模板中使用它们。所以最正确的途径应该是:
routes.MapHttpRoute(
name: "Optional parameters route",
routeTemplate: "api/{controller}"
);