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 returnsHttpResponse
object for this request. The following code shows how to return 500 response with JSON content: