如何使用参数强制重定向?

How do I force a redirect with a parameter?

我有一个必须 URL 编码的参数值。因此我的理解是它必须在 URL 的末尾作为查询字符串发送,而不是主要 URL 的一部分。我已经通过直接将 URL 粘贴到浏览器中成功地测试了这一点。

我正在尝试重定向到 URL 的:

Server/Application/Area/Controller/Action/?id=xyz

但是当我使用

return RedirectToAction("Action", "Controller", new { area = "Area", id = Url.Encode(uniqueId) });

我被发送到

Server/Application/Area/Controller/Action/xyz

如何阻止这种情况发生?

这是因为您的默认路线是;

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Site", action = "Index", id = UrlParameter.Optional }
            );

如果您想继续使用这条路线,您应该必须更改 url 中的 id 参数。

但是如果默认路由中省略了 id 参数,您的操作将按预期重定向。

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}",
                defaults: new { controller = "Site", action = "Index"}
            );

从默认路由中删除 ID

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

或将您的参数名称从 id 更改为其他名称。

希望对您有所帮助。