使用$ Windows.Location和ASP.NET MVC编码特殊字符的问题



我有一个JavaScript代码,在其中我将窗口进行窗口。将其location与.NET MVC操作。ID是一个数字E.x。1234,虽然名称是具有特殊字符的名称。前任。"Røed"

$window.location = "/mycontroller/myaction/?id=" + query.id + "&name=" + query.name;

在提琴手中,我可以看到请求URL变为:mydomain.com/controller/action/?id=1234&name=røED

当我在我的ASP.NET MVC控制器中尝试从request.querystring获取查询字符串值时,我会得到一些看起来像双重编码的字符串的东西:

public ActionResult MyAction(LandingPage currentPage, string state)
{
    string queryString = Request.QueryString.ToString();
    var cultureName = CultureInfo.CurrentCulture.Name;

querystring变为:" id = 1234& name = r%u00f8ed"

您可以看到,请求URL的编码看起来与ASP.NET中的编码相同。为什么?

我需要在我的应用程序(Røed(中进一步使用解码名称。我该如何完成?

在JavaScript侧尝试此操作(确保正确编码每个部分(:

$window.location = "/mycontroller/action/?id=" + encodeURIComponent(query.id) + "&name=" + encodeURIComponent(query.name);

在MVC侧:

public ActionResult Action(string id, string name)
{
}

或现在使用您的示例,您已经提供了:

public ActionResult MyAction(LandingPage currentPage, string state, string id = null, string name = null)
{
    if (id != null && name != null)
    {
    }
}

然后应正确解释名称。因为您正在直接使用Querystring,所以它是编码的查询字符串。

如果您真的需要,则可以使用HttpUtility.ParseQueryString(...)解析查询字符串,这将为您提供NameValueCollection,但这不是做事的正确方法。

最新更新