【问题标题】:ASP.Net MVC: Passing a string parameter to an action using RedirectToAction()ASP.Net MVC:使用 RedirectToAction() 将字符串参数传递给操作
【发布时间】:2012-02-25 17:59:03
【问题描述】:

我想知道如何使用 RedirectToAction() 传递字符串参数。

假设我有这条路线:

routes.MapRoute(
  "MyRoute",
  "SomeController/SomeAction/{id}/{MyString}",
  new { controller = "SomeController", action = "SomeAction", id = 0, MyString = UrlParameter.Optional }
);

在 SomeController 中,我有一个执行重定向的操作,如下所示:

return RedirectToAction( "SomeAction", new { id = 23, MyString = someString } );

我尝试使用 someString = "!@#$%?&* 1" 进行此重定向,但无论我是否对字符串进行编码,它总是失败。我尝试使用 HttpUtility.UrlEncode(someString)、HttpUtility.UrlPathEncode(someString) 和 Uri.EscapeUriString(someString) 对其进行编码。

所以我求助于我们的 TempData 来传递一些字符串,但我仍然很想知道如何使上面的代码工作,只是为了满足我的好奇心。

【问题讨论】:

  • 您是否尝试在web.config 中更改relaxedUrlToFileSystemMappingrequestPathInvalidCharacters
  • @EricYin 不,我没有。我不知道这两个参数。我会调查他们。

标签: asp.net-mvc-3 url routing redirect url-encoding


【解决方案1】:

我认为问题可能出在您的路线顺序或控制器中。这是我开始工作的一些代码。

路线定义

        routes.MapRoute(
            "TestRoute",
            "Home/Testing/{id}/{MyString}",
            new { controller = "Home", action = "Testing", id = 0, MyString = UrlParameter.Optional }
        );

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

// note how the TestRoute comes before the Default route

控制器动作方法

    public ActionResult MoreTesting()
    {
        return RedirectToAction("Testing", new { id = 23, MyString = "Hello" });
    }

    public string Testing(int id, string MyString)
    {
        return id.ToString() + MyString;
    }

当我浏览到 /Home/MoreTesting 时,我会在我的浏览器中获得所需的 "23Hello" 输出。你能发布你的路线和你的控制器代码吗?

【讨论】:

  • 我的代码适用于 MyString = "Hello"。问题在于特殊字符。试试 MyString = "!@#$%?&* 1",你就会明白我的意思了。
【解决方案2】:

好的,我知道这个问题已经有几天了,但我不确定你是否解决了这个问题,所以我看了一下。我已经玩了一段时间了,这就是问题所在以及如何解决它。

您遇到的问题是导致问题的特殊字符是众多(我认为是 20 个)特殊字符之一,例如 % 和 "。

在您的示例中,问题是 % 字符。 正如Priyankhere所指出的:

路由值作为 URL 字符串的一部分发布。

Url 字符串(不是查询字符串参数)无法处理 %(%25)、"(%22) 等。 此外,正如Lee Gunn 在同一篇文章中指出的那样: http://localhost:1423/Home/Testing/23/!%40%23%24%25%3f%26*%201 - (这会爆炸)

解决此问题的方法之一是从路由映射中删除{MyString}。使您的根映射如下所示:

routes.MapRoute(
    "TestRoute",
    "Home/Testing/{id}",
    new { controller = "Home", action = "Testing", id = 0, MyString = UrlParameter.Optional }
);

这将导致帖子生成:

http://localhost:1423/Home/Testing/23?MyString=!%2540%2523%2524%2525%2B1

现在,当您设置MyString 时,它将变成一个查询字符串参数,可以正常工作。 我确实尝试过,它确实奏效了。

Priyank 在我上面链接的 SO 帖子中也提到,您也许可以使用自定义 ValueProvider 来解决这个问题,但您必须按照他的链接文章来检查这是否适用于您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    • 2014-03-03
    • 2011-09-06
    • 2012-10-17
    • 2019-06-01
    • 2021-02-14
    • 2011-07-25
    相关资源
    最近更新 更多