问题
Given the following controller:
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// POST api/values
[HttpPost]
public ActionResult<string> Post([FromBody] Model req)
{
return $"Your name is {req.Name}";
}
}
public class Model
{
[Required] public string Name { get; set; }
}
}
if I post an empty body {}
, the response is:
{
"errors": {
"Name": [
"The Name field is required."
]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "80000002-0002-ff00-b63f-84710c7967bb"
}
I would like to change this response, so it becomes easier to automatically pass the error message on to the user. So I would like it to look more like this:
{
"error": 999,
"message": "Field 'name' is required."
}
I tried to extend the RequiredAttribute
-class like so:
public class MyRequiredAttribute : RequiredAttribute
{
public MyRequiredAttribute()
{
ErrorMessage = "{0} is required";
}
}
which sadly only changes the returned string in the collection, like so
{
"errors": {
"Name": [
"Name is required"
]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "80000006-0000-ff00-b63f-84710c7967bb"
}
回答1:
When utilizing a controller with the ApiController attribute applied, ASP.NET Core automatically handles model validation errors by returning a 400 Bad Request with ModelState as the response body. It is related to Automatic HTTP 400 responses . You could customize BadRequest response like below :
services.AddMvc()
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = actionContext =>
{
var modelState = actionContext.ModelState;
return new BadRequestObjectResult(FormatOutput(modelState));
};
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
Customize the FormatOutput
method to your whims.
public List<Base> FormatOutput(ModelStateDictionary input)
{
List<Base> baseResult = new List<Base>();
foreach (var modelState in input.Values)
{
foreach (ModelError error in modelState.Errors)
{
Base basedata = new Base();
basedata.Error = StatusCodes.Status400BadRequest;
basedata.Message =error.ErrorMessage;
baseResult.Add(basedata);
}
}
return baseResult;
}
public class Base
{
public int Error { get; set; }
public string Message { get; set; }
}
回答2:
Try and add this code below the [Requried] annotation
[StringLength(150, ErrorMessage = "Name length can't be less than 1 or greater than 150 characters.", MinimumLength = 1)]
Hope this helps...
来源:https://stackoverflow.com/questions/57233662/response-to-missing-required-properties-in-asp-net-core