是否可以在web.config中添加响应http头?

Mar*_*ijn 30 asp.net

在我的应用程序中,我需要设置一个http响应头.我想在web.config中这样做.

Adr*_*ark 60

执行此操作的最佳方法<customHeaders>web.config文件的元素.请注意,这仅适用于IIS 7及更高版本.

添加示例标头的配置如下:

<configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Content-Language" value="*" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅IIS"自定义标头"配置参考页面


Mar*_*ijn 11

解决方案 最后,经过长时间的搜索,我找到了解决方案 使用以下代码创建一个类:

public class myHTTPHeaderModule : IHttpModule
{

    #region IHttpModule Members

    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("Content-Language", "*");

    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)

(不要问我为什么要使用这个活动,但它有效..)

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

    <httpModules>
        <add type="namespace.myHTTPHeaderModule, assembly name" name="headers" />
        <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </httpModules>
Run Code Online (Sandbox Code Playgroud)

就是这样!