Mak*_*jer 5 asp.net-mvc-4 asp.net-web-api
我想为我的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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后我将它添加到Global.asax中的全局装配器:
configuration.Filters.Add(new ValidationActionFilter());
它适用于我的大多数操作,但与具有可选和可空请求参数的操作不一样.
例如:
我创建了一条路线:
routes.MapHttpRoute(
name: "Optional parameters route",
routeTemplate: "api/{controller}",
defaults: new { skip = UrlParameter.Optional, take = UrlParameter.Optional });
Run Code Online (Sandbox Code Playgroud)
我的一个动作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));
}
Run Code Online (Sandbox Code Playgroud)
现在,当我请求此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."
}
]
Run Code Online (Sandbox Code Playgroud)
我认为这不应该作为验证错误出现,因为这些参数都是可选的和可空的.
有没有人遇到过这个问题并找到了解决方案?
看来你搞乱了 Web API 和 MVC 之间的代码,你应该使用Web API 中的RouteParameter而不是MVC 中的UrlParameter
routes.MapHttpRoute(
name: "Optional parameters route",
routeTemplate: "api/{controller}",
defaults: new { skip = RouteParameter.Optional, take = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
但:
路由skip和take的默认参数对路由机制不起作用,因为您只是在查询字符串中使用它们,而不是在路由模板中使用它们。所以最正确的路线应该是:
routes.MapHttpRoute(
name: "Optional parameters route",
routeTemplate: "api/{controller}"
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3094 次 |
| 最近记录: |