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

需要哪些不会引发任何异常属性,将只有错误信息,所以你可以在异常过滤器。

相关问题