I need to access ModelState
in Asp.net Core 2.1 Middleware, but this is just accessible from Controller
.
For example I have ResponseFormatterMiddleware
and in this Middleware I need to ignore ModelState
error and show it's errors in 'Response Message':
public class ResponseFormatterMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ResponseFormatterMiddleware> _logger;
public ResponseFormatterMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_logger = loggerFactory?.CreateLogger<ResponseFormatterMiddleware>() ?? throw new ArgumentNullException(nameof(loggerFactory));
}
public async Task Invoke(HttpContext context)
{
var originBody = context.Response.Body;
using (var responseBody = new MemoryStream())
{
context.Response.Body = responseBody;
// Process inner middlewares and return result.
await _next(context);
responseBody.Seek(0, SeekOrigin.Begin);
using (var streamReader = new StreamReader(responseBody))
{
// Get action result come from mvc pipeline
var strActionResult = streamReader.ReadToEnd();
var objActionResult = JsonConvert.DeserializeObject(strActionResult);
context.Response.Body = originBody;
// if (!ModelState.IsValid) => Get error message
// Create uniuqe shape for all responses.
var responseModel = new GenericResponseModel(objActionResult, (HttpStatusCode)context.Response.StatusCode, context.Items?["Message"]?.ToString());
// Set all response code to 200 and keep actual status code inside wrapped object.
context.Response.StatusCode = (int)HttpStatusCode.OK;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(responseModel));
}
}
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class ResponseFormatterMiddlewareExtensions
{
public static IApplicationBuilder UseResponseFormatter(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ResponseFormatterMiddleware>();
}
}
[Serializable]
[DataContract]
public class GenericResponseModel
{
public GenericResponseModel(object result, HttpStatusCode statusCode, string message)
{
StatusCode = (int)statusCode;
Result = result;
Message = message;
}
[DataMember(Name = "result")]
public object Result { get; set; }
[DataMember(Name = "statusCode")]
public int StatusCode { get; set; }
[DataMember(Name = "message")]
public string Message { get; set; }
[DataMember(Name = "version")]
public string Version { get; set; } = "V1.0"
}
and this is my excpected result:
{
"result": null,
"statusCode": 400,
"message": "Name is required",
"version": "V1"
}
but now the observed result is:
{
"result": {
"Name": [
"Name is required"
]
},
"statusCode": 400,
"message": null,
"version": "V1"
}
ModelState
simply doesn’t exist in general middleware. It’s an MVC concept. – Mnemonics