简体   繁体   English

如何在asp.net mvc中的查询字符串值中使用/

[英]how can use / in querystring value in asp.net mvc

I used ASP.NET MVC5, I have a URL like this: 我使用了ASP.NET MVC5,我有一个类似这样的URL:

localhost:/product/12/nexus5x/quartz 本地主机:/产品/ 12 / nexus5x /石英

product :controller; 12 :id; nexus5x/quartz:name

But it's returning a 404 error because the last param in the url contains / and I don't have routing to support that. 但这返回了404错误,因为url中的最后一个参数包含/而我没有路由来支持它。 How can I do this? 我怎样才能做到这一点? Sometimes the last param ( productName ) contains / . 有时最后一个参数( productName )包含/

The first solution is replace / with - but for some product I couldn't replace that. 第一个解决方案是用/替换-但对于某些产品,我无法替换。

You need to encode the URL. 您需要 URL进行编码 URL encoding involves converting the characters so that they can be included in the query string. URL编码涉及转换字符,以便可以将其包含在查询字符串中。 The character / is encoded to %2F . 字符/被编码为%2F

So the URL will become /product/12/nexus5x%2Fquartz 因此,该网址将变为/product/12/nexus5x%2Fquartz

To encode the value in JavaScript you can call the encodeURI method. 要使用JavaScript编码值,可以调用encodeURI方法。

var productName = "nexus5x/quartz";
var encodedProductName = encodeURI(productName);

To encode the value in C# you can call the Uri.EscapeUriString method. 要使用C#对值进行编码,可以调用Uri.EscapeUriString方法。

I believe that you should be able to use a catch all route. 我相信您应该能够使用全部捕获的路线。 Just prefix an asterisk '*' to the last token. 只需在最后一个标记之前加上星号 “ *”即可。

Here is an example using Route attribute: 这是使用Route属性的示例:

[Route("product/{id}/{*name}")]

The parameter 'name' here should catch everything past 'id' , even if that includes a slash. 即使此处包含斜杠,此处的参数“名称”也应捕获“ id”之后的所有内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM