0

我只是使用.Net構建webapi。我在Post方法中有一個Car Model,並且其中一個字段具有Required屬性和一個錯誤消息類型。問題是,當我沒有在指定的字段中輸入任何內容時,我的消息沒有顯示,我只收到一條消息,如空字符串(「」)。另外,如果我有一個int類型的字段,並且我沒有在該字段中輸入任何內容,則模型狀態無效。如何避免轉換錯誤?如果我不在必填字段中輸入任何內容,如何獲得正確的錯誤消息?提前致謝。ModelState驗證

這是我的代碼:

我的模型:

public class Car 
{ 
    public Guid Id { get; set; } 

    public bool IsActive { get; set; } 

    [Required(ErrorMessageResourceName = "RequiredName", ErrorMessageResourceType = typeof(Car_Resources))] 
    public string Name { get; set; } 

    [Required(ErrorMessageResourceName = "RequiredNumber", ErrorMessageResourceType = typeof(Car_Resources))] 
     public string Number { get; set; } 
} 

控制器:

[ValidateModelAttribute] 
public IHttpActionResult Post([FromBody]Car car) 
{ 
} 

ValidateModelAttribute方法:

public override void OnActionExecuting(HttpActionContext actionContext) 
{ 
    if (!actionContext.ModelState.IsValid) 
    { 
     var errors = new List<string>(); 
     foreach (var state in actionContext.ModelState) 
     { 
      foreach (var error in state.Value.Errors) 
      { 
       errors.Add(error.ErrorMessage); 
      } 
     } 

     actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors); 
    } 
} 
+0

當你說你只有一個像空字符串的消息 - 如果你使用ErrorMessage而不是ErrorMessageResourceName,會發生什麼 - 我想知道它是否工作,但它只是沒有從資源中獲取消息( RESX)? – Alex

+0

不,它不工作。我認爲這是因爲我沒有爲Number設置任何值。此外,ModelState正試圖將該字段轉換爲其默認值。例如Id是Guid,但我收到一個字符串作爲Id,然後,由於轉換,ModelState將不再有效。 – CalinCosmin

回答

1

我找到了答案。這是不是最好的,但如果你對性能的使用[Required]屬性,那麼您可以使用此:

public override void OnActionExecuting(HttpActionContext actionContext) 
{ 
    if (!actionContext.ModelState.IsValid) 
    { 
     var errors = new List<string>(); 
     foreach (var state in actionContext.ModelState) 
     { 
      foreach (var error in state.Value.Errors) 
      { 
       if (error.Exception == null) 
       { 
        errors.Add(error.ErrorMessage); 
       } 
      } 
     } 

     if (errors.Count > 0) 
     { 
      actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors); 
     } 
    } 
} 

需要哪些不會引發任何異常屬性,將只有錯誤信息,所以你可以在異常過濾器。

相關問題