ASP.Net MVC:使用RedirectToAction()传递字符串参数给操作

9
我想知道如何使用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 来传递 someString,但仍然很好奇如何使上述代码能够正常工作,只是为了满足我的好奇心。


你试过在 web.config 中更改 relaxedUrlToFileSystemMappingrequestPathInvalidCharacters 吗? - Eric Yin
@EricYin 不,我没有。我不知道这两个参数。我会研究一下。 - Jean-François Beauchamp
2个回答

3

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

你遇到的问题是特殊字符引起的问题之一(我认为有20个),例如%和"。

在你的例子中,问题是%字符。 正如Priyank here所指出的那样:

路由值作为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来解决这个问题,但您必须遵循他们链接的文章来检查是否适用于您。

3

我认为问题可能出现在你的路由顺序或控制器中。这里是一些我成功运行的代码。

路由定义

        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"。你能发布你的路由和控制器代码吗?


2
我的代码可以处理 MyString = "Hello"。问题在于特殊字符。尝试使用 MyString = "!@#$%?&* 1",你就会明白我的意思。 - Jean-François Beauchamp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接