In ASP.Net Core 2.0, I am trying to return a message formatted as json or xml with a status code. I have no problems returning a custom message from a controller, but I don't know how to deal with it in a middleware.
My middleware class looks like this so far:
public class HeaderValidation
{
private readonly RequestDelegate _next;
public HeaderValidation(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
// How to return a json or xml formatted custom message with a http status code?
await _next.Invoke(httpContext);
}
}
To fill response in middleware use httpContext.Response
property that returns HttpResponse
object for this request. The following code shows how to return 500 response with JSON content:
public async Task Invoke(HttpContext httpContext)
{
if (<condition>)
{
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
string jsonString = JsonConvert.SerializeObject(<your DTO class>);
await context.Response.WriteAsync(jsonString, Encoding.UTF8);
// to stop futher pipeline execution
return;
}
await _next.Invoke(httpContext);
}