【问题标题】:URL rewriting in ASP.NET Core MVC won't use back referencing correctlyASP.NET Core MVC 中的 URL 重写不会正确使用反向引用
【发布时间】:2021-05-19 21:37:51
【问题描述】:

这是Parameter binding to either route or querystring in ASP.NET MVC Core 的延续。我在 .NET Core 3.1 中有一个 ASP.NET MVC 网站,我正在尝试 URL 重写以将查询字符串值放入路径中,例如 /api/Values?id=1。我已经从https://github.com/dotnet/AspNetCore.Docs/tree/master/aspnetcore/fundamentals/url-rewriting/samples/ 下载了示例应用程序,并将我自己的规则添加到IISUrlRewrite.xml 文件中,如下所示:

<rewrite>
  <rules>
      <rule name="my rule" stopProcessing="true">
          <match url="^api/(\w+)$" />
          <condition>
              <add input="{QUERY_STRING}" pattern="id=([0-9]+)" />
          </condition>
          <action type="Rewrite" url="api/{R:1}/{C:1}" appendQueryString="false"/>
      </rule>
  </rules>
</rewrite>

但是,当我运行应用程序并转到 /api/Values?id=1 时,重写后的 URL 是 /api/Values/?id=1。所以我们可以看到规则被应用了,{R:1}(来自路径的反向引用)被正确应用了,但是应该是 ID 号的{C:1} 是整个查询字符串值。

所以我尝试将规则更改为这样:

      <rule name="some other rule" stopProcessing="true">
          <match url="^api/(\w+)$" />
          <condition>
              <add input="{QUERY_STRING}" pattern="id=1" />
          </condition>
          <action type="Rewrite" url="api/{R:1}/1" appendQueryString="false"/>
      </rule>

这样做使得重写的 URL 为api/Values/1?id=1。因此,即使appendQueryString 属性设置为false,似乎仍会附加整个查询字符串。

我错过了什么?谢谢。

【问题讨论】:

    标签: c# asp.net-mvc url-rewriting asp.net-core-mvc


    【解决方案1】:

    根据源代码,这似乎是内置功能,asp.net核心的appendquerystring属性与IIS的不同,它会追加新的查询字符串而不是删除它。

    source codes 是这样的:

            if (pattern.IndexOf(Uri.SchemeDelimiter, StringComparison.Ordinal) >= 0)
            {
                string scheme;
                HostString host;
                PathString path;
                QueryString query;
                FragmentString fragment;
                UriHelper.FromAbsolute(pattern, out scheme, out host, out path, out query, out fragment);
    
                if (query.HasValue)
                {
                    if (QueryStringAppend)
                    {
                        request.QueryString = request.QueryString.Add(query);
                    }
                    else
                    {
                        request.QueryString = query;
                    }
                }
                else if (QueryStringDelete)
                {
                    request.QueryString = QueryString.Empty;
                }
    
                request.Scheme = scheme;
                request.Host = host;
                request.Path = path;
            }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 2019-02-08
    • 2017-09-10
    • 2011-08-13
    • 2023-03-15
    • 2011-02-21
    相关资源
    最近更新 更多