ASP.NET MVC 4 RC Web API ModelState错误,可选的url参数可以为空

时间:2012-08-10 15:09:16

标签: asp.net-mvc-4 asp.net-web-api

我想为我的Web API创建一个全局的valdiation属性。所以我跟着tutorial,最后得到以下属性:

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));
}

现在,当我请求此网址时: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."
}
]

我认为这不应该作为验证错误出现,因为这些参数都是可选的和可以为空的。

有没有人遇到过这个问题并找到了解决方案?

2 个答案:

答案 0 :(得分:4)

您可能还想避免/禁止GET请求中原始类型的模型验证。

public class ModelValidationFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.ModelState.IsValid && actionContext.Request.Method != HttpMethod.Get)
            { ...

答案 1 :(得分:2)

如果您在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 }
    );

可是:

您的路线跳过拍摄的默认参数不会对您的路线机制起任何作用,因为您只在查询字符串中使用它们,而不是在路线模板中使用它们。所以最正确的路线应该是:

routes.MapHttpRoute(
    name: "Optional parameters route", 
    routeTemplate: "api/{controller}"
    );