用于设置响应ContentType的中间件

Mat*_*ias 16 c# owin-middleware asp.net-core asp.net-core-1.0

在我们基于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";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,尝试context.Response.ContentType在调用其余的中间件链后设置会产生以下异常:

System.InvalidOperationException: "Headers are read-only, response has already started."
Run Code Online (Sandbox Code Playgroud)

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

Set*_*Set 11

尝试使用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);
}
Run Code Online (Sandbox Code Playgroud)


And*_*toy 6

使用 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);
}
Run Code Online (Sandbox Code Playgroud)