Middleware to set response ContentType

后端 未结 2 791
情深已故
情深已故 2021-02-12 23:39

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

相关标签:
2条回答
  • 2021-02-13 00:20

    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);
    }
    
    0 讨论(0)
  • 2021-02-13 00:33

    Using an overload of OnStarting method:

    public async Task Invoke(HttpContext context)
    {
        context.Response.OnStarting(() =>
        {
            if (context.Response.StatusCode == (int) HttpStatusCode.OK &&
                context.Request.Path.Value.EndsWith(".map"))
            {
                context.Response.ContentType = "application/json";
            }
    
            return Task.CompletedTask;
        });
    
        await nextMiddleware.Invoke(context);
    }
    
    0 讨论(0)
提交回复
热议问题