How to URL encode parameters in ASP .NET MVC

不打扰是莪最后的温柔 提交于 2019-12-17 14:47:41

问题


I have the following code in my view:

<%= Html.ActionLink(
           "View item", 
           "Index", 
            "Items", 
            new 
            { 
                itemName = Model.ItemName 
            }, 
            null) %>

I have a problem when the item name contains a sharp (#) or the percent symbol (%).

  • When the item name is "name#with#sharp#", the controller receives only the first part of the name until the first sharp (only receives "name").

  • When the item name is "name%with%percent" I get an error: HTTP error 400 - Bad request.

I not sure if this is a problem with the URL encoding, because it works with other conflictive chars such as:

;
=
+
,
~
[blank]

Do you know how could I address this issue?

Thanks in advance.


回答1:


I'm assuming you have a route setup and your url looks something like this:

http://localhost/Items/Index/name%25with%25percent - (this will blow up)

as opposed to this:

http://localhost/Items/Index/?itemName=name%25with%25percent - (query string is ok)

So an option would be to remove the "itemName" property from your route (in your RouteCollection) so that Html.ActionLink will render the Url using itemName as a QueryString parameter.

As @Priyank says, the problem is because the itemName is part of the Url (not a QueryString parameter) and it contain illegal characters.




回答2:


Since these routedvalues are posted as part of URL string, they will be treated as separate values, separated by # and %. There are couple options for handle your case.

You will have to implement your custom ValueProvider (IValueProvider and especially RouteDataValueProvider) to handle your custom need. One programmer had an issue with character '/' and he hacked it here http://mrpmorris.blogspot.com/2012/08/asp-mvc-encoding-route-values.html

Second is to store values in TempData which persists across two request and use them.

Hope this helps to think in right direction.




回答3:


You should be able to just use the UrlHelper instance of your view to do this for you. Try giving this a shot:

<%= Html.ActionLink( "View item", "Index", "Items", new { itemName = Url.Encode(Model.ItemName) }, null) %>

Update

After testing, it seems explicitly encoding like I did above seems to be less accurate and will cause the server to double-encode (eg - % will come out as %2525 in the url).



来源:https://stackoverflow.com/questions/5901049/how-to-url-encode-parameters-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!