如何在ASP.NET MVC Razor中编码'/'

时间:2021-06-10 16:38:20

Controller:

public ActionResult Tool(string id)
{
  // Code goes here . . 
}

View:

<a href="/Home/@item.Type/@Url.Encode(item.Title)" id="toolTitleLink">@item.Title</a>

From the code above @item.Title can have special characters like '/' sample link is http://localhost:39727/Home/Tool/C+Compiler+For+The+Pic10%2f12%2f16+Mcus when I try to navigate to that link Tool Controller was not called. I used @Url.Encode but still Controller was not called.

从上面的代码@ item.Title可以有特殊字符,如'/'示例链接是http:// localhost:39727 / Home / Tool / C + Compiler + For + The + Pic10%2f12%2f16 + Mcus当我尝试导航到该链接未调用工具控制器。我使用了@ Url.Encode但是还没有调用Controller。

1 个解决方案

#1


2  

Unfortunately even if you use System.Uri.EscapeDataString instead of Url.Encode like so:

不幸的是,即使您使用System.Uri.EscapeDataString而不是Url.Encode,如下所示:

<a href="/Home/@item.Type/@System.Uri.EscapeDataString(item.Title)" id="toolTitleLink">@item.Title</a>

The rendered page will have the slashes encoded (look in the 'view source' of the page) the browser will still decode them.

渲染的页面将具有编码的斜杠(查看页面的“视图源”),浏览器仍将对其进行解码。

You have two options, as far as I can see:

据我所知,您有两种选择:

  1. Use a different character - make your own escape (so to speak ;)) - for example using tilda (~) or whatever else URL valid character you want, in order to replace the forward slash.

    使用不同的字符 - 让你自己逃避(可以这么说;)) - 例如使用tilda(〜)或你想要的任何其他URL有效字符,以替换正斜杠。

  2. Create a special route for the action with a catch-all at the end and parse things from the action.

    为操作创建一个特殊路径,最后使用catch-all并从操作中解析事物。

#1


2  

Unfortunately even if you use System.Uri.EscapeDataString instead of Url.Encode like so:

不幸的是,即使您使用System.Uri.EscapeDataString而不是Url.Encode,如下所示:

<a href="/Home/@item.Type/@System.Uri.EscapeDataString(item.Title)" id="toolTitleLink">@item.Title</a>

The rendered page will have the slashes encoded (look in the 'view source' of the page) the browser will still decode them.

渲染的页面将具有编码的斜杠(查看页面的“视图源”),浏览器仍将对其进行解码。

You have two options, as far as I can see:

据我所知,您有两种选择:

  1. Use a different character - make your own escape (so to speak ;)) - for example using tilda (~) or whatever else URL valid character you want, in order to replace the forward slash.

    使用不同的字符 - 让你自己逃避(可以这么说;)) - 例如使用tilda(〜)或你想要的任何其他URL有效字符,以替换正斜杠。

  2. Create a special route for the action with a catch-all at the end and parse things from the action.

    为操作创建一个特殊路径,最后使用catch-all并从操作中解析事物。