简体   繁体   English

在IIS 8.5托管的.NET WebAPI 2中添加自定义标头

[英]Adding custom headers in .NET WebAPI 2 hosted by IIS 8.5

I wrote a WEBAPI application with C# that works fine while developing but when in production, hosted by IIS 8.5 I got a problem. 我用C#编写了一个WEBAPI应用程序,该应用程序在开发过程中运行良好,但是在IIS 8.5托管的生产环境中却遇到了问题。

In order to enable CORS (Cross Origin Resource Sharing) in my controller, I implemented the OPTION action: 为了在我的控制器中启用CORS(跨源资源共享),我实现了OPTION动作:

[HttpOptions]
[AllowAnonymous]
public HttpResponseMessage Options()
{
    HttpResponseMessage res = new HttpResponseMessage();

    res.Headers.Add("Access-Control-Allow-Headers", "User-Agent, Content-Type, Accept, X-ApplicationId, Authorization, Host, Content-Length");
    res.Headers.Add("Access-Control-Allow-Methods", "POST");
    res.Headers.Add("Access-Control-Allow-Origin", "*");
    res.StatusCode = HttpStatusCode.OK;
    return res;
}

As I wrote before everything works ok on Visual Studio but in production, when I make an OPTIONS request using Fiddler, the answer is always: 正如我之前写的那样,在Visual Studio上一切正常,但在生产中,当我使用Fiddler发出OPTIONS请求时,答案总是:

HTTP/1.1 200 OK
Allow: OPTIONS, TRACE, GET, HEAD, POST
Server: Microsoft-IIS/8.5
Public: OPTIONS, TRACE, GET, HEAD, POST
X-Powered-By: ASP.NET
Date: Fri, 05 Feb 2016 16:56:20 GMT
Content-Length: 0
Proxy-Connection: keep-alive

I know that is possible to add Header's key statically in IIS but, in my controller, I need to add a Custome Header with dynamic values like that: 我知道可以在IIS中静态添加Header的键,但是在我的控制器中,我需要添加具有以下动态值的Custome Header:

res.Headers.Add("X-App-Limit-Remaining", getRemainingCalls());

Anybody knows how to overwrite/change HTTP headers from a C# WEB API hosted by IIS 8. ? 谁知道如何从IIS 8托管的C#WEB API覆盖/更改HTTP标头。

Many Thanks, 非常感谢,

Luke 路加

You can tap into the request pipeline by using a System.Net.Http.DelegatingHandler 您可以使用System.Net.Http.DelegatingHandler进入请求管道

Reference: HTTP Message Handlers in ASP.NET Web API 参考: ASP.NET Web API中的HTTP消息处理程序

You can add custom handlers to the pipeline. 您可以将自定义处理程序添加到管道中。 Message handlers are good for cross-cutting concerns that operate at the level of HTTP messages (rather than controller actions). 消息处理程序非常适合在HTTP消息级别(而不是控制器操作)上运行的跨领域关注点。 For example, a message handler might: 例如,消息处理程序可能会:

  • Read or modify request headers. 读取或修改请求标头。
  • Add a response header to responses. 向响应添加响应头。
  • Validate requests before they reach the controller. 在请求到达控制器之前对其进行验证。

Using your rate limit example here is a simplified handler: 这里使用您的速率限制示例是一个简化的处理程序:

public class WebApiRateLimitHandler : DelegatingHandler {

    //Override the SendAsync Method to tap into request pipeline
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
        Debug.WriteLine("Process request");
        // Call the inner handler.
        Task<HttpResponseMessage> response = base.SendAsync(request, cancellationToken);
        Debug.WriteLine("Process response");
        return response.ContinueWith(task => {
            var httpResponse = task.Result;
            httpResponse.Headers.Add("X-App-Limit-Remaining", getRemainingCalls());
            return httpResponse;
        });        
    }
}

Adding a Handler to the Pipeline 将处理程序添加到管道

Message handlers are called in the same order that they appear in MessageHandlers collection. 消息处理程序的调用顺序与它们在MessageHandlers集合中出现的顺序相同。 Because they are nested, the response message travels in the other direction. 因为它们是嵌套的,所以响应消息沿另一个方向传播。 That is, the last handler is the first to get the response message. 也就是说,最后一个处理程序是第一个获取响应消息的处理程序。

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        //Order handlers are added is important. First in last out
        config.MessageHandlers.Add(new WebApiRateLimitHandler());
        config.MessageHandlers.Add(new SomeOtherMessageHandler());

        // Other code not shown...
    }
}

There is also an X-HTTP-Method-Override example. 还有一个X-HTTP-Method-Override示例。 Checkout the referenced link for more examples. 查看参考链接以获取更多示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM