在 asp.net 页面中获取 Header 响应值(带破折号)

Get Header value of response in asp.net page with dashes

我知道这很容易,但我做不到。我在下面有回复 header。

X-Exposure-Server:EastUS2

我是这样吐出来的

<span>@Response.Headers["X-Exposure-Server"]</span>

然而,它是空白的。为什么?

回复Headers

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server: Microsoft-IIS/8.5
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Exposure-Server: EastUS2
Access-Control-Allow-Origin: *
X-UA-Compatible: IE=Edge,chrome=1
Date: Tue, 19 Apr 2016 04:39:53 GMT
Content-Length: 11017

如果您要将自定义 header 添加到响应中,那么 available.Just 快速检查 Response.Headers 的值 watch.Tried 您的 scenario.I 添加了我的响应 header Response.AddHeader("myheader", "myheadervalue");并尝试在视图中使用它 - @Response.Headers["myheader"],它显示了 value.Only,显示了 mvc 添加的 header。

只有通过 code.So 设置密钥才能访问密钥检查此方法 创建一个继承 IHttpModule 的 class 并实现它。

public class HTTPHeaderModule : IHttpModule
{
    public void Dispose()
    {

    }

    public void Init(HttpApplication context)
    {
        context.EndRequest += new EventHandler(context_EndRequest);
    }

    void context_EndRequest(object sender, EventArgs e)
    {
        HttpResponse response = HttpContext.Current.Response;

        response.AddHeader("X-Exposure-Server","EastUS2e");
        //You can read this(EastUS2e) value from web.config
    }
}

现在在 HttpModule 部分的 web.config 中添加一行:

<httpModules>
    <add name="HTTPHeaderModule" , type="HTTPHeaderModule" />
 </httpModules>

MSDN 参考:

http://msdn.microsoft.com/en-us/library/aa719858%28VS.71%29.aspx

我让它工作的唯一方法是在 BeginRequest 中设置它,EndRequest 是在页面呈现之后。

protected void Application_BeginRequest()
        {
            HttpContext.Current.Response.AddHeader("X-Exposure-Server", Config.Settings.ServerRegion);
        }