设置响应ContentType的中间件 [英] Middleware to set response ContentType
问题描述
在基于ASP.NET Core的Web应用程序中,我们需要执行以下操作:某些请求的文件类型应获取自定义ContentType作为响应.例如. .map
应该映射到application/json
.在完整" ASP.NET 4.x中以及与IIS结合使用时,可以使用web.config <staticContent>/<mimeMap>
来实现此功能,我想用自定义ASP.NET Core中间件来替换此行为.
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";
}
}
}
不幸的是,在调用中间件链的其余部分之后尝试设置context.Response.ContentType
会导致以下异常:
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?
推荐答案
尝试使用HttpContext.Response.OnStarting
回调.这是发送标头之前触发的最后一个事件.
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);
}
这篇关于设置响应ContentType的中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!