2016-07-19 46 views
0

我驗證使用ModelState.IsValid輸入:爲空類型無效的ModelState錯誤消息

[HttpGet] 
[Route("subjects")] 
[ValidateAttribute] 
public IHttpActionResult GetSubjects(bool? isActive = null) 
{ 
    //get subjects 
} 

如果我通過在URI ~/subjects/?isActive=abcdef,我得到的錯誤消息:

值「ABCDEF」是對於Nullable`1無效。

如果輸入參數不能爲空

public IHttpActionResult GetSubjects(bool isActive){ 
    //get subjects 
} 

我得到的錯誤信息:

值 'ABCDEF' 不是有效的布爾值。

我想重寫消息如果可爲空的類型,所以我可以維護消息(「值'abcdef'是無效的布爾。」)。我怎麼能這樣做,因爲在ModelState錯誤我沒有得到數據類型。我正在實施驗證作爲自定義ActionFilterAttributeValidationAttribute)。

+0

你可以設置你'ModelState'想要的任何錯誤消息。 – lorond

+0

我可以將它設置爲我想要的樣子「值'abcdef'對於布爾值無效」,但問題是錯誤對象沒有被驗證參數的類型信息(bool,int等)。 – alltej

回答

2

您可以更改格式類型轉換錯誤消息的回調。例如,讓我們把它定義爲權Global.asax.cs

public class WebApiApplication : HttpApplication 
{ 
    protected void Application_Start() 
    { 
     ModelBinderConfig.TypeConversionErrorMessageProvider = this.NullableAwareTypeConversionErrorMessageProvider; 

     // rest of your initialization code 
    } 

    private string NullableAwareTypeConversionErrorMessageProvider(HttpActionContext actionContext, ModelMetadata modelMetadata, object incomingValue) 
    { 
     var target = modelMetadata.PropertyName; 
     if (target == null) 
     { 
      var type = Nullable.GetUnderlyingType(modelMetadata.ModelType) ?? modelMetadata.ModelType; 
      target = type.Name; 
     } 

     return string.Format("The value '{0}' is not valid for {1}", incomingValue, target); 
    } 
} 

對於非可空類型Nullable.GetUnderlyingType將返回null,在這種情況下,我們會使用原始類型。

不幸的是,你不能訪問默認的字符串資源,如果你需要本地化錯誤信息,你必須自己做。

另一種方法是實現您自己的IModelBinder,但這不是您的特定問題的好主意。

0

Lorond的回答突出瞭如何靈活地使用asp.net web api來讓程序員自定義API的許多部分。當我看到這個問題時,我的思考過程是在一個動作過濾器中處理它,而不是覆蓋配置中的某些東西。

public class ValidateTypeAttribute : ActionFilterAttribute 
{ 
    public ValidateTypeAttribute() { } 

    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
     string somebool = actionContext.Request.GetQueryNameValuePairs().Where(x => x.Key.ToString() == "somebool").Select(x => x.Value).FirstOrDefault(); 

     bool outBool; 
     //do something if somebool is empty string 
     if (!bool.TryParse(somebool, out outBool)) 
     { 
      HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest); 
      response.ReasonPhrase = "The value " + somebool + " is not valid for Boolean."; 
      actionContext.Response = response; 
     } 
     else 
     { 
      base.OnActionExecuting(actionContext); 
     } 
    } 

然後裝點操作方法與動作過濾器控制器屬性

+0

「somebool」在這裏被硬編碼。因爲它將是一個屬性,我需要在不同的控制器中大量使用,我們不知道參數名稱和可空參數類型(bool?,int?),所以我不能硬編碼參數名稱和類型。 – alltej

+0

你可以繞過一個類型測試。 – Bill

相關問題