URL-encode parameters in ActionLink?

谁都会走 提交于 2021-01-28 00:46:34

问题


I have the following route registered;

        routes.MapRoute(
            "LocationsByArea",                                              
            "Locations/{system}/{storage}/{area}",          
            new { controller = "StorageLocation", action = "Index" },
            null
        );

...and the following code in my view;

<%= Html.ActionLink("Platser", "Index", "StorageLocation", new { system = Model.System, storage = Model.Storage, area = item.Name }, null)%>

My problem is when the "area = item.Name" contains a colon, e.g. "Area 4:1". If I click the rendered link I get HTTP-error 400, Bad reqest. I guess I have to encode my area parameter in some way, but I cant figure out how. Any help is apreciated.

Thanks!


回答1:


The built-in encoding/decoding does not work, so I suggest you roll your own, like this:

namespace MyProject.Helpers
{
    public static class JobNameHelper
    {
        public static string JobNameEncode(string jobname)
        {
            return jobname.Replace(":", "---colon---");
        }

        public static string JobNameDecode(string jobname)
        {
            return jobname.Replace("---colon---", ":");
        }

    }
}



回答2:


Can you not just use

Server.UrlEnconde(item.Name)

Or am I missing something?

In your routing you may have to use Server.UrlDecde as well although I think It should decode for you on request.

Try using the Routing Debugger to see what the url router is getting passed, then you can see where the decoding needs to happen




回答3:


ASP.NET 3.5 SP1 and earlier have a number of restrictions on which URLs are valid. In ASP.NET 4 most of these issues have been fixes (or are at least customizable via web.config). I think that the colon character, even when encoded, might not be allowed in ASP.NET 3.5 SP1 and earlier due to security concerns. Allowing colons can be a security problem when performing file checks since they are a little-known syntax for NTFS Alternate Data Streams.

I recommend trying to choose a character other than a colon for these purposes. Maybe a comma, semi-colon, or equal sign might work instead?



来源:https://stackoverflow.com/questions/1819368/url-encode-parameters-in-actionlink

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