public class ModelValidationMiddleware
{
private readonly RequestDelegate _next;
public ModelValidationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (!context.Request.Path.StartsWithSegments("/api"))
{
await _next(context);
return;
}
var modelState = context.Features.Get<Microsoft.AspNetCore.Mvc.ModelBinding.Validation.IValidationFeature>()?.ModelState;
if (modelState != null && !modelState.IsValid)
{
var errors = modelState.Values.SelectMany(v => v.Errors.Select(e => e.ErrorMessage)).ToList();
var response = new ApiResponse(false, "Model validation failed", errors: errors);
context.Response.StatusCode = 400; // Bad Request
context.Response.ContentType = "application/json";
var responseText = JsonSerializer.Serialize(response);
await context.Response.WriteAsync(responseText);
return;
}
await _next(context);
}
}
标签:modelState,errors,next,context,var,validate,public
From: https://www.cnblogs.com/miaokela/p/18134494