ModelState Validation
I just build a webapi using .Net. I have a Car Model in a post method and one of the field has Required property and an error message type. The problem is that when I don't enter anything in that specified field my message is not shown, I got only a message like an empty string ( "" ). Also, if I have a field of type int and I don't enter anything in that field the model state is not valid. How can I skip the conversion errors and how can I get the correct error message if I don't enter anything in required fields ? Thanks in advance.
This is my code:
My Model:
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; }
}
Controller:
[ValidateModelAttribute]
public IHttpActionResult Post([FromBody]Car car)
{
}
ValidateModelAttribute method:
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);
}
}
I found an answer. It's not the best one but if you use [Required]
attribute on properties then you can use this:
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);
}
}
}
The properties which are required will not throw any exception, will have only the error message so you can filter on exception.
链接地址: http://www.djcxy.com/p/67994.html上一篇: Web API中的ModelState Errormessage为空
下一篇: ModelState验证