Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core 2.0 - How to return custom json or xml response from middleware?

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);
    }
}
like image 947
philipp-fx Avatar asked Mar 15 '18 16:03

philipp-fx


People also ask

How do I return XML and JSON from Web API in .NET Core?

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 { ... }

How do I return JSON in Web API NET Core?

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 .

How do I redirect in middleware NET Core?

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 .


1 Answers

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);
}
like image 72
Set Avatar answered Sep 28 '22 04:09

Set