如何从IIS重写模块获得JavaScript(或其他)重写的URL

How can I get rewritten URL in JavaScript (or otherwise) from IIS Rewrite module?

本文关键字:重写 其他 URL JavaScript IIS 模块      更新时间:2023-09-26

我正在为单页应用程序编写HTML页面,并希望将其发布到我当前的ASP主机上,所以我使用IIS URL重写模块向/index.HTML发送大量请求

<rule name="Section">
  <match url="sections/(.*)" />
  <action type="Rewrite" url="index.html?section={R:1}" logRewrittenUrl="true" />
</rule>

我想做的是用JavaScript获得重写的查询字符串,尽管这似乎是不可能的。在静态html页面中有没有方法可以获得重写的查询字符串?window.location.href是原始url,而不是重写后的url。

最简单的方法是将重写后的URL作为响应体的一部分进行转储:

<input type="hidden" id="__rewritten_url" value="<%=Request.ServerVariables("URL")%>" />

或者,您可以将重写后的URL附加为Response Header,然后发出Ajax请求并从中提取该标头。因此,您的web.config看起来像:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="Section">
                 <match url="sections/(.*)" />
                 <action type="Rewrite" url="index.html?section={R:1}" logRewrittenUrl="true" />
            </rule>
        </rules>
        <outboundRules>
            <rule name="AppendRewrittenResponseHeader" patternSyntax="Wildcard">
                <match serverVariable="RESPONSE_URL" pattern="*" />
                <action type="Rewrite" value="{URL}" />
            </rule>
        </outboundRules>
    </rewrite>
</system.webServer>

然后在客户端(为了简洁起见,使用jQuery):

$.ajax({
        type: "HEAD",
        url: location.href,
        success: function(message,text,response)
              {
              var myRewrittenUrl = response.getResponseHeader('URL');
              }
    });