如何在MVC Core控制器引发异常时不丢弃的中间件中设置HTTP响应标头?

时间:2019-02-19 09:36:04

标签: c# asp.net-core httpresponse

以下程序使用两个路由创建一个简单的ASP.NET MVC Core 2.2.0站点:

  • /success-返回字符串“成功响应”。
  • /failure-引发异常,导致返回500

另外还有一个中间件,该中间件将HTTP响应标头设置为X-Added-Key / X-Added-Value。它使用OnStarting事件执行此操作,根据documentation“添加一个要在响应标头发送到客户端之前调用的委托。”

但是,我看到的是当MVC处理/failure路由的异常时,我的HTTP响应标头被擦除了;中间件肯定受到攻击,但是响应缺少X-Added-Key HTTP响应标头。我怀疑这已经完成了here

我应该如何设置HTTP响应标头,以便MVC在发生异常时不将其丢弃?我在这里的用例是,我们希望返回一个请求ID,以便API使用者在希望报告错误时可以给我们提供参考,因此无论控制器是否遇到异常,都应将其返回。

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;

namespace ResponseHeadersSanityCheck
{
    internal static class Program
    {
        static void Main(string[] args)
        {
            WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build()
            .Run();
        }
    }

    public sealed class ExampleController : Controller
    {
        [HttpGet, Route("success")]
        public string Success() => "Success Response";

        [HttpGet, Route("failure")]
        public string Failure() => throw new Exception("Failure Response");
    }

    public sealed class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            app
                .Use(async (HttpContext context, Func<Task> next) =>
                {
                    context.Response.OnStarting(() =>
                    {
                        context.Response.Headers.Add("X-Added-Key", "X-Added-Value");
                        return Task.CompletedTask;
                    });
                    await next();
                })
                .UseMvc();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以捕获中间件处理之间的异常。

尝试

document.onkeydown = windowskey;
document.onkeyup = printscreenkey;


function windowskey(e) {
  switch (e.which) {
    case 91: // left windows
    case 92: // right windows
      $("#documentViewer").hide();

      break;
  }
}

function printscreenkey(e) {
  switch (e.which) {
    case 44: // print screen
      copyToClipboard();
      $("#documentViewer").show();

      break;
    case 91: // left windows
    case 92: // right windows
      $("#documentViewer").show();

      break;
  }


}

更新:

app.Use(async (HttpContext context, Func<Task> next) =>
    {
        context.Response.OnStarting(() =>
        {
            context.Response.Headers.Add("X-Added-Key", "X-Added-Value");
            return Task.CompletedTask;
        });
        try
        {
            await next();
        }
        catch (Exception ex)
        {

        }
    }).UseMvc();

更新:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseDeveloperExceptionPage();
    app.Use(async (HttpContext context, Func<Task> next) =>
        {
            context.Response.OnStarting(() =>
            {
                context.Response.Headers.Add("X-Added-Key", "X-Added-Value");
                return Task.CompletedTask;
            });
            await next();
        }).UseMvc();            
}