【问题标题】:Middleware to set response ContentType设置响应 ContentType 的中间件
【发布时间】:2016-06-20 09:08:29
【问题描述】:

在我们基于 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."

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

【问题讨论】:

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


    【解决方案1】:

    尝试使用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);
    }
    

    【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-15
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      相关资源
      最近更新 更多