无法标题附加“因人而异”来回应 [英] Unable to append 'Vary' header to response

查看:241
本文介绍了无法标题附加“因人而异”来回应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个添加因人而异:接受编码头到响应的文件,我COM preSS,的as建议早期

I'm trying to add a Vary: Accept-Encoding header to the response to files that I compress, as advised earlier.

然而,出于某种原因,这是不可能的 - 无论是从Visual Studio的测试服务器或IIS服务器

However, for some reason this is not possible - either from the Visual Studio test server, or an IIS server.

我有以下的code:

if (url.Contains(".js") || url.Contains(".aspx") || url.Contains(".css"))
{
    app.Response.AppendHeader("Vary", "Accept-Encoding");
    app.Response.AppendHeader("Varye", "Accept-Encoding"); // for testing
    app.Response.AppendHeader("Varye", "Accept-Things");   // for testing
    app.Response.AppendHeader("Vary", "Accept-Stuff");     // for testing
    app.Response.AppendHeader("Var", "Accept-Items");      // for testing

    encodings = encodings.ToLower();

    if (encodings.Contains("gzip") || encodings == "*")
    {
        app.Response.Filter = new GZipStream(baseStream, CompressionMode.Compress);
        app.Response.AppendHeader("Content-Encoding", "gzip");

    }
}

这导致以下响应头:

Status=OK - 200
Server=ASP.NET Development Server/10.0.0.0
Date=Fri, 21 Oct 2011 12:24:11 GMT
X-AspNet-Version=4.0.30319
Varye=Accept-Encoding, Accept-Things
Var=Accept-Items
Content-Encoding=gzip
Cache-Control=public
Etag="1CC8F2E9D772300"
Content-Type=text/css
Content-Length=16200
Connection=Close

正如你所看到的,因人而异头是不是present。用类似的语法意义的标题是present,所以一定有什么东西在什么地方,取出Vary标头在发送前。

As you can see, the Vary header is not present. Meaningless headers with similar syntax are present, so there must be something, somewhere, taking out the Vary header before it is sent.

我不知道这是否是相关的,但这里是我在web.config中定义我的COM pression模块:

I don't know if it is relevant, but here is where I define my compression module in web.config:

<httpModules>
    <add name="CompressionModule" type="Utility.HttpCompressionModule"/>
</httpModules>

(凡Utility.HttpCom pressionModule是其中code摘录我上面提供的类属)。

(Where Utility.HttpCompressionModule is the class which the code excerpt I provided above belongs to.)

为什么我不能添加因人而异头?

编辑:埃里克·C'S解决方案给我留下了code是这样的:

Eric C's solution has left me with code like this:

if (url.Contains(".js") || url.Contains(".aspx") || url.Contains(".css"))
{
    app.Response.Cache.SetVaryByCustom("Accept-Encoding");

    encodings = encodings.ToLower();

    if (encodings.Contains("gzip") || encodings == "*")
    {
        app.Response.Filter = new GZipStream(baseStream, CompressionMode.Compress);
        app.Response.AppendHeader("Content-Encoding", "gzip");

    }

不过,标题是这样的:

But, the headers look like this:

Status=OK - 200
Server=ASP.NET Development Server/10.0.0.0
Date=Mon, 24 Oct 2011 09:26:37 GMT
Content-Encoding=gzip
Cache-Control=public
Etag="1CC7A09FDE77300"
Vary=*
Content-Type=application/x-javascript
Content-Length=44447
Connection=Close

(不知道为什么,这是应用程序/ x-的JavaScript 作为其在HTML设置为文/ JavaScript的 ,但是这是不相关的。)

(No idea why this is application/x-javascript as its set in the HTML as text/javascript, but this is irrelevant.)

正如你所看到的,我现在有一个变化的头,但它被设置为因人而异= * ,而不是因人而异=接受编码,因为你会从COM pression模块在我的code期望的。

As you can see, I now have a vary header, but it is set as Vary=* rather than Vary=Accept-Encoding, as you would expect from my code in the compression module.

这是怎么回事?我如何获得因人而异头设置是否正确?

What is going on here? How do I get the Vary header set correctly?

第二个编辑:
我要粘贴源$ C ​​$ C全班。没有更给它比我已经发布,但它可能有助于给我做什么的把握:

Second I'm going to paste the source code for the whole class. There isn't much more to it than I have already posted, but it might help to give a grasp of exactly what I'm doing:

public class HttpCompressionModule : IHttpModule
{
    /// <summary>
    /// Initializes a new instance of the <see cref="AjaxHttpCompressionModule"/> class.
    /// </summary>
    public HttpCompressionModule()
    {
    }

    #region IHttpModule Members

    /// <summary>
    /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
    /// </summary>
    void IHttpModule.Dispose()
    {

    }

    /// <summary>
    /// Initializes a module and prepares it to handle requests.
    /// </summary>
    /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
    void IHttpModule.Init(HttpApplication context)
    {
        context.BeginRequest += (new EventHandler(this.context_BeginRequest));
    }

    #endregion

    /// <summary>
    /// Handles the BeginRequest event of the context control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    void context_BeginRequest(object sender, EventArgs e)
    {            
        HttpApplication app = (HttpApplication)sender;
        string encodings = app.Request.Headers.Get("Accept-Encoding");
        Stream baseStream = app.Response.Filter;


        if (string.IsNullOrEmpty(encodings))
            return;


        string url = app.Request.RawUrl.ToLower();

        if (url.Contains(".js") || url.Contains(".css") || url.Contains("ajax.ashx"))
        {
            app.Response.Cache.SetVaryByCustom("Accept-Encoding");

            encodings = encodings.ToLower();

            if (encodings.Contains("gzip") || encodings == "*")
            {
                app.Response.Filter = new GZipStream(baseStream, CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "gzip");

            }
            else if (encodings.Contains("deflate"))
            {
                app.Response.Filter = new DeflateStream(baseStream, CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "deflate");
            }
        }
    }
}

此外,这里是我的web.config文件的system.web节:

Further, here is the System.Web section of my web.config file:

<system.web>
    <!--<compilation debug="true"></compilation>-->
    <trace enabled="true" traceMode="SortByTime"/>
    <httpRuntime executionTimeout="180"/>
    <globalization culture="en-GB" uiCulture="en-GB"/>
    <!-- custom errors-->
    <customErrors mode="Off">
    </customErrors>
    <!-- Membership -->
    <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
        <providers>
            <clear/>
            <add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="SQLServerAuth" applicationName="mycompany" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="1024"/>
        </providers>
    </membership>
    <!-- Roles -->
    <roleManager enabled="true" cacheRolesInCookie="true" defaultProvider="SqlProvider">
        <providers>
            <clear/>
            <add connectionStringName="SQLServerAuth" applicationName="mycompany" name="SqlProvider" type="System.Web.Security.SqlRoleProvider"/>
        </providers>
    </roleManager>
    <!-- Authentication -->
    <anonymousIdentification enabled="false"/>
    <authentication mode="Forms">
        <forms name=".AUTH" protection="All" timeout="2" path="/">
        </forms>
    </authentication>
    <httpModules>
        <add name="CompressionModule" type="Utility.HttpCompressionModule"/>
    </httpModules>
</system.web>

有没有多说。还有就是我们正在与该网站没有做其他非标准的东西,这我知道。任何想法?

There isn't much more to say. There is no other non-standard stuff that we are doing with the site, that I know about. Any ideas?

推荐答案

正如其他人所说,这是一个<一个href=\"https://connect.microsoft.com/VisualStudio/feedback/details/758474/iis-gzip-com$p$pssion-filter-removes-$p$p-existing-vary-header\"相对=nofollow>已知问题与IIS COM pression模块专门覆盖因人而异头和的修补程序

As mentioned by others, this is a known issue with the IIS compression module overwriting the Vary header specifically and has been addressed by hotfix.

如果你不能确保安装修复程序,然后另一个解决办法是使用的 IIS URL重写在你的web.config:

If you can't ensure the hotfix is installed then another workaround is to append the header using IIS URL Rewrite in your Web.config:

<configuration>
  <system.webServer>
    <rewrite>
      <outboundRules>
        <rule name="Append 'Vary: X-Requested-With' header" patternSyntax="ECMAScript">
          <match serverVariable="RESPONSE_VARY" pattern=".+" />
          <action type="Rewrite" value="{R:0}, X-Requested-With" replace="true" />
        </rule>
        <rule name="Set 'Vary: X-Requested-With' header if no others" patternSyntax="ECMAScript">
          <match serverVariable="RESPONSE_VARY" pattern=".+" negate="true" />
          <action type="Rewrite" value="X-Requested-With" />
        </rule>
      </outboundRules>
    </rewrite>
  </system.webServer>
</configuration>

这篇关于无法标题附加“因人而异”来回应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆