如何在没有查询参数的情况下将URL重写加倍?

Kee*_*ker 5 c# asp.net iis-7 url-rewriting

我必须关注以下网址:

http://example.org/sessionstuff/kees/view.aspx?contentid=4&itemid=5

它需要重写,以便它将:

http://example.org/sessionstuff/view.aspx?site=kees&contentid=4&itemid=5

基本上它将kees取值并将其作为site参数.我正在使用IIS URL重写模块,它使用我的web.config中的规则.我已将以下代码添加到我的web.config中:

<rule name="RedirectSite" stopProcessing="true">
    <match url="^(\D[^/]*)/(.*)$" />
    <action type="Rewrite" url="{R:2}?site={R:1}" />
</rule>
Run Code Online (Sandbox Code Playgroud)

一切正常,但当我做回发时,site参数加倍.我在.aspx页面上使用以下代码测试了这个:

<h3>Querystring</h3>
<ul>
    <% foreach (string key in Request.QueryString.Keys)
        Response.Write(String.Format("<li><label>{0}:</label>{1}</li>", key, Request.QueryString[key])); %>
</ul>
<asp:Button runat="server" Text="Postback" />
Run Code Online (Sandbox Code Playgroud)

第一次

Querystring
site: kees
contentid: 4
itemid: 5
Run Code Online (Sandbox Code Playgroud)

第二次

Querystring
site: kees, kees <--- double
contentid: 4
itemid: 5
Run Code Online (Sandbox Code Playgroud)

如何防止site参数重复?每个回发都会添加另一个值.

注意:必须存在其他查询参数,因此使用appendQueryString="false"似乎不是一个选项.

Tom*_*ler 2

site=如果 URL 已包含参数(无论它位于查询字符串中的位置),则看起来可以通过不重写 URL 来解决此问题。那么我们该怎么做呢?

\n\n

在这里查看第 9 号:http://ruslany.net/2009/04/10-url-rewriting-tips-and-tricks/

\n\n

我现在没有办法测试这个,但我认为这样的东西应该有效:

\n\n
<rule name="Query String Rewrite">\n\xc2\xa0 <match url="^(\\D[^/]*)/(.*)$" />\n\xc2\xa0 <conditions>\n\xc2\xa0\xc2\xa0\xc2\xa0 <add input="{QUERY_STRING}" pattern="^((?!site=).)*$" />\n\xc2\xa0 </conditions>\n  <action type="Rewrite" url="{R:2}?site={R:1}" />\n</rule>\n
Run Code Online (Sandbox Code Playgroud)\n\n

注意:我不擅长规则重写,但是^((?!site=).)*$当字符串不包含时,这个正则表达式会匹配site=,并且这是您希望重写规则运行的时候,因此我将其添加为条件。我想你也许能够更有效地做到这一点。

\n\n

我在这里想做的是:让我们重写规则,但前提是它尚未包含参数site

\n\n

我希望这足以让您回答这个问题!

\n\n

===

\n\n

这似乎有效:

\n\n
<rule name="RedirectSite" stopProcessing="true">\n    <match url="^(\\D[^/]*)/(.*)$" />\n    <conditions>\n        <add input="{QUERY_STRING}" pattern="^((?!site=).)*$" />\n    </conditions>\n    <action type="Rewrite" url="{R:2}?site={R:1}" />\n</rule>\n\n\n<rule name="RedirectSite2" stopProcessing="true">\n    <match url="^(\\D[^/]*)/(.*)$" />\n    <conditions>\n        <add input="{QUERY_STRING}" pattern="site=" />\n    </conditions>\n    <action type="Rewrite" url="{R:2}"  />\n</rule>\n
Run Code Online (Sandbox Code Playgroud)\n