Alice52 / c-tutorial

The repository is about c, including c, csharp, cpp.
MIT License
0 stars 0 forks source link

[mvc] controller config about model mapping 「from」 #11

Open Alice52 opened 4 years ago

Alice52 commented 4 years ago

requirement

  1. mapping model failed should be 400 Bad Request
  2. default it will without control, but we can make it in control by using below solution: InvalidModelStateResponseExtension

InvalidModelStateResponseExtension

/// <summary>
/// Return common http response for model validation error
/// https://docs.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-2.2#validation-failure-error-response
/// </summary>
public static class InvalidModelStateResponseExtension
{
    public static void ConfigureInvalidModelStateResponseApiBehavior(this IServiceCollection services)
    {

        services.Configure<ApiBehaviorOptions>(options =>
        {
            options.InvalidModelStateResponseFactory = context =>
            {
                var problemDetails = new ValidationProblemDetails(context.ModelState);
                var errorResponse = new ErrorResponse()
                {
                    Code = ErrorMessages.INVALID_PARAMETER_ERROR_CODE.ToString(),
                    Message = problemDetails.Title,
                    Parameters = problemDetails.Errors
                };

                return new BadRequestObjectResult(errorResponse);
            };
        });

    }
}

controller

[Route("api/[controller]/[action]")]
[ApiController]
public class xxxController : ControllerBase 
{
    // expose uri: xxx/UpdateStatus
    [HttpPost]
    [SwaggerResponse((int)HttpStatusCode.OK)]
    public ActionResult UpdateStatus([FromBody] ReqestModel requestBody)
    {
         return Ok();       
    }

    [HttpGet("{path-args}")]
    public IList<resposneModel> Getxx(string path-args)
    {
        // .netcore will do http resposne, default is application/json, 
        // fotunately, we can specify data format in startup
        return new List<resposneModel>();
    }
}

start up

  1. register to use this extension
service.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.ConfigureInvalidModelStateResponseApiBehavior();