简体   繁体   中英

What is the flow of ASP.NET Core Web API pipeline if I do not have Content-Type at all in my header?

I'm trying to solve this problem where if a client does not have content type in their header before even reaching my controller I want to display my OWN error message. Not the [ApiController] generic problems details messages, but entirely my own JSON Object. I've been trying to figure this out and I at least know that having the [ApiController] attribute over my controller will give me problem details response for 4XX error codes. I removed this and now I have empty response bodies. I would like the same status code just a different body/object as the response. What would be the best way to approach this? I would like to know the flow so I can catch this error before hand and return my response with my own JSON object

You can solve this using Middleware. The following is a sample Middleware class that you can create and hook up to the HTTP Pipeline

public class InterceptContentType
{
    private RequestDelegate _next;

    public InterceptContentType(RequestDelegate next)
    {
        this._next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        // This is where you can intercept the content type as shown below
        // and perform what you need
        context.Request.Headers[HeaderNames.ContentType] = "application/xml";
        await _next.Invoke(context);
    }
}

Hooking up this class to your HTTP Pipeline is as simple as adding the below statement to your Configure() method within Startup.cs class

app.UseMiddleware<InterceptContentType>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM