c# - 通过 web.config 删除查询字符串

标签 c# asp.net iis web-config url-rewrite-module

在我的网站上,我的 URL 有时会收到由我们的系统附加的查询字符串参数。

因此,与其看起来像这样:http://www.domain.com?myquery=blahhttp://www.domain.com,它有网址 http:http://www.domain.com?myquery=blah&theirpara=blahhttp://www.domain.com?theirpara=blah .

当用户使用“theirpara”参数访问时,我想在没有它的情况下进行 301 重定向到 URL。

我试过使用 URL 重写模块,但没有真正取得任何进展。如果可能的话,最好在 IIS/web.config 级别而不是 Response.RedirectPermanent 级别执行此操作。

我认为使用规则(URL 写入模块)进行设置会很好,但老实说,我不知道如何解决这个问题。我正在使用以下规则删除结尾的斜杠,但不确定如何根据需要修改它。

<!--To always remove trailing slash from the URL-->
<rule name="Remove trailing slash" stopProcessing="true">
  <match url="(.*)/$" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
  </conditions>
  <action type="Redirect" redirectType="Permanent" url="{R:1}" />
</rule>

关于如何设置它有什么想法吗?

最佳答案

如果您正在寻找一个非常通用的规则来删除 theirpara 但保留任何其他查询字符串参数,那么您将不得不处理以下情况

  1. 是一个人:?theirpara=123 -> /
  2. 首先是:?theirpara=123&ourparams=456 -> ?ourparams=456
  3. 它在中间:?our1=123&theirpara=456&our2=789 -> ?our1=123&our2=789
  4. 最后一个:?ourparams=123&theirpara=456 -> ?ourparams=123

我写了一个规则来处理这些情况,但在情况 4 中留下了尾随的 & 号,我希望它足以让你开始。

<rule name="Redirect on theirpara" stopProcessing="true">
    <match url="^(.*)$" />
        <conditions>
            <add input="{QUERY_STRING}" pattern="^(.*)theirpara=([^=&amp;]+)&amp;?(.*)$" />
        </conditions>
    <action type="Redirect" url="/{R:0}?{C:1}{C:3}" appendQueryString="false" />
</rule>

关于c# - 通过 web.config 删除查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13322179/

相关文章:

asp.net - Windows "forms"身份验证 - <拒绝用户 ="?"> 重定向到外部页面!

IIS SMTP - 服务器响应为 : 5. 7.1 无法中继传出地址,仍然无法正常工作

asp.net - 在 IIS 8.0 上设置 asp.net 项目时出现 HTTP 错误 404.17

c# - 将现有项目添加到解决方案的效果

c# - 验证 SSL 证书

.net - 从 MySQL 中检索 10 条记录?

javascript - 如何在 ASP.NET 用户控件中存储 css 和 js

iis - 我如何映射 http ://localhost:8080 to http://mysites in iis7?

c# - 使用 LINQ 对字符串数组进行排序

c# - 与 android xamarin 中的命名空间混淆