2012-08-10 53 views
5

我想爲我的Web API創建一個全局的valdiation屬性。所以我也跟着tutorial,並結束了與以下屬性:ASP.NET MVC 4 RC Web API ModelState錯誤的可選url參數可爲空

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全球fitlers:

configuration.Filters.Add(new ValidationActionFilter());

它的偉大工程與大多數我的行動但並不像預期的那樣具有可選和可空請求參數的動作。

例如:

我創建了一個路線:

而且在動作我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

似乎搞砸的Web API和MVC之間的代碼,您應該使用RouteParameter從網絡API,而不是UrlParameter從MVC

routes.MapHttpRoute(
    name: "Optional parameters route", 
    routeTemplate: "api/{controller}", 
    defaults: new { skip = RouteParameter.Optional, take = RouteParameter.Optional } 
    ); 

但是:

的默認參數您route skip and take不會爲您的路由機制發揮任何作用,因爲您只是在查詢字符串中使用它們,而不是在路由模板中使用它們。所以最糾正路線應該是:

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

好一點,但仍然不解決問題這裏。這兩個參數都是「必需的」,儘管它們可以爲空,但在ModelState字典中有錯誤。你知道一種將行爲參數標記爲不需要的方法嗎? – 2012-08-13 07:26:42

+0

您是否在代碼中嘗試了這種解決方案? – 2012-08-13 07:32:11

+0

至於你的問題,使用可選參數 – 2012-08-13 07:35:42

4

您也可能希望避免對基本類型的GET請求/抑制模型驗證..

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

你能詳細說一下嗎? – 2017-09-27 13:32:03