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);
}
}
In order to return XML using an IActionResult method, you should also use the [Produces] attribute, which can be set to “application/xml” at the API Controller level. [Produces("application/xml")] [Route("api/[controller]")] [ApiController] public class LearningResourcesController : ControllerBase { ... }
To return data in a specific format from a controller that inherits from the Controller base class, use the built-in helper method Json to return JSON and Content for plain text. Your action method should return either the specific result type (for instance, JsonResult ) or IActionResult .
Use AddRedirectToHttps to redirect HTTP requests to the same host and path using the HTTPS protocol. If the status code isn't supplied, the middleware defaults to 302 - Found. If the port isn't supplied: The middleware defaults to null .
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With