为什么不将字符串参数路由到操作?

Why isn't string parameter being routed to an action?

在我的 MVC5 应用程序中,我试图将字符串传递给操作。

PodcastsController 我有一个动作叫做 Tagged:

public ActionResult Tagged(string tag)
{
    return View();
}

例如,如果我想将字符串 Test 传递给 Tagged 操作,它在 url:

中看起来像这样

/Podcasts/Tagged/Test

我有这样设置的路线:

routes.MapRoute(
       "Podcasts",
       "Podcasts/Tagged/{tag}",
       new { controller = "Podcasts", action = "Tagged", tag = UrlParameter.Optional }
    );

编辑 我这样调用 Tagged 操作:

if (!string.IsNullOrEmpty(tagSlug))
{
    return RedirectToAction("Tagged", "Podcasts", new { tag = tagSlug });
}

When I set a break point on the Taggedaction, tag is always null

谁能看出我做错了什么?

我很确定路线有问题,但我不知道是什么...

它一定是这样工作的....

然后去http://localhost:64147/podcast/tagged/hi接收他作为tag的值

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "MyRoute",
        url: "podcast/tagged/{tag}",
        defaults: new { controller = "Podcasts", action = "Tagged", tag = UrlParameter.Optional }
    );

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

很抱歉我在这里问,但是您是否检查过您的路线是否在任何其他可能重叠的路线之前?

路由是按顺序完成的。选择与给定参数对应的第一条路线,因此如果您首先拥有这条路线

{controller}/{action}/{id}

然后

Podcasts/Tagged/{tag}

你会得到 null 因为选择了第一条路线

路线顺序实际上很重要

你得到 null 的原因是因为你实际上并没有在你的代码中传递一个名为 tag 的参数:

if (!string.IsNullOrEmpty(tagSlug))
{
    return RedirectToAction("Tagged", "Podcasts", new { tagSlug });
}

当您省略 属性 名称时,它采用变量名称,因此您实际上传递了一个您的操作不接受的变量 tagSlug。试试这个:

if (!string.IsNullOrEmpty(tagSlug))
{
    return RedirectToAction("Tagged", "Podcasts", new { tag = tagSlug });
}