Passing in a querystring with a space?

2019-07-26 17:44发布

I have an action like this:

public ActionResult UserDetails(string id)
{
}

context.MapRoute(
            "Admin_Default",
            "{controller}/{action}/{id}",
            new { action = "Index", controller = "Start", id = UrlParameter.Optional }
        );

In another view i have a list with users from the standard membership management in .net Idea is that you click on a username to show the details and this works, only if the username is in one word. I recently encountered a username that looks like this:

Steven C.H. Andersson

So i use this to produce the link:

@Html.ActionLink(Model.UserName, "UserDetails", new { controller = "Security", id = HttpUtility.UrlEncode(Model.UserName) })

But when i click on it, i get: HTTP Error 404.11 - Not Found

If i click on a normal username that is one word, it works like a charm.

I assume that the route config is not understanding this request, question is how to get it to work?

Update

Link:

<a href="/Security/UserDetails/Steven%2bC.H.%2bAndersson">Steven C.H. Andersson</a>

2条回答
走好不送
2楼-- · 2019-07-26 18:34

I had the same problem, here is how I solved it, but I am not sure it is the best way. I am keen to hear a more elegant solution.

In the view file:

@Html.ActionLink(Model.UserName, "UserDetails", new { controller = "Security", id = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Model.UserName)) })

In the controller file:

id = Encoding.UTF8.GetString(Convert.FromBase64String(id))
查看更多
smile是对你的礼貌
3楼-- · 2019-07-26 18:47

The encoding is obviously wrong, as it encodes spaces as "%2b", which is "+". You're passing not a query string argument, but a part of path, so you need to use HttpUtility.UrlPathEncode()

查看更多
登录 后发表回答