Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Middleware to set response ContentType

In our ASP.NET Core based web application, we want the following: certain requested file types should get custom ContentType's in response. E.g. .map should map to application/json. In "full" ASP.NET 4.x and in combination with IIS it was possible to utilize web.config <staticContent>/<mimeMap> for this and I want to replace this behavior with a custom ASP.NET Core middleware.

So I tried the following (simplified for brevity):

public async Task Invoke(HttpContext context)
{
    await nextMiddleware.Invoke(context);

    if (context.Response.StatusCode == (int)HttpStatusCode.OK)
    {
        if (context.Request.Path.Value.EndsWith(".map"))
        {
            context.Response.ContentType = "application/json";
        }
    }
}

Unfortunately, trying to set context.Response.ContentType after invoking the rest of the middleware chain yields to the following exception:

System.InvalidOperationException: "Headers are read-only, response has already started."

How can I create a middleware that solves this requirement?

like image 855
Matthias Avatar asked Jun 20 '16 09:06

Matthias


People also ask

What happens when a terminal middleware is used in the request pipeline?

Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline.


1 Answers

Try to use HttpContext.Response.OnStarting callback. This is the last event that is fired before the headers are sent.

public async Task Invoke(HttpContext context)
{
    context.Response.OnStarting((state) =>
    {
        if (context.Response.StatusCode == (int)HttpStatusCode.OK)
        {
           if (context.Request.Path.Value.EndsWith(".map"))
           {
             context.Response.ContentType = "application/json";
           }
        }          
        return Task.FromResult(0);
    }, null);

    await nextMiddleware.Invoke(context);
}
like image 114
Set Avatar answered Sep 16 '22 13:09

Set