Skip to main content
 首页 » 编程设计

c#中ASP.NET Core 使用中间件修改 HTTP 请求 header

2025年12月25日38JustinYoung

我需要做的就是将[Connection] HTTP header 从“Keep-alive”修改为小写“keep-alive”。

我写了这个类(class),

public class PreRequestModifications 
{ 
 
    private readonly RequestDelegate _next; 
 
    public PreRequestModifications(RequestDelegate next) 
    { 
        _next = next; 
    } 
 
    public async Task Invoke(HttpContext context) 
    { 
        // Does not get called when making an HTTPWebRequest.    
        await _next.Invoke(context);               
    } 
} 

并在启动时注册,

 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
 {     
     app.UseMiddleware<PreRequestModifications>(); 
 } 

但是当我执行 await httpWebRequest.GetResponseAsync();

时,不会调用 Invoke 方法

请您参考如下方法:

因此,当发出请求和发回响应时,中间件就会受到影响。实际上,这意味着您可以像这样两次调用 Invoke 方法:

public async Task Invoke(HttpContext context) 
{ 
  ModifyRequest(context); 
  await _next(context); 
  ModifyResponse(context); 
} 

因此您可以在 ModifyResponse 方法中修改响应。

微软的文档会说得更清楚:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.1

希望这有帮助。