用于设置响应ContentType的中间件

时间:2016-06-20 09:08:30

标签: asp.net-core asp.net-core-1.0 owin-middleware

在我们基于ASP.NET Core的Web应用程序中,我们需要以下内容:某些请求的文件类型应该获得自定义ContentType的响应。例如。 .map应映射到application/json。在“完整”的ASP.NET 4.x中,与IIS结合使用,可以使用web.config <staticContent>/<mimeMap>,我希望用自定义的ASP.NET Core中间件替换此行为。

所以我尝试了以下(简化为简洁):

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会产生以下异常:

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

如何创建解决此要求的中间件?

2 个答案:

答案 0 :(得分:8)

尝试使用HttpContext.Response.OnStarting回调。这是在发送标头之前触发的最后一个事件。

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);
}

答案 1 :(得分:4)

使用OnStarting方法的重载:

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);
}
相关问题