MVC 路由参数根本不起作用

MVC routing parameters not working at all

我一直在寻找解决方案,但即使是最简单的示例也无法正常工作。传递单个参数 {id} 可以成功,但这是唯一有效的参数。将单个参数更改为其他任何参数都会失败。在下面的示例中,多个参数也会失败。似乎唯一可行的参数是 "id".

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

        routes.MapRoute(
          name: "Servers",
          url: "{controller}/{action}/{id}/{a}",
          defaults: new
          {
            controller = "Test"
          }
        );
    }

public class TestController : Controller
{
  [HttpGet]
  public ActionResult Monster(string id, string a)
  {
    return Json(new { success = id }, JsonRequestBehavior.AllowGet);
  }
}

urllocalhost/Test/Monster/hi成功读取参数为"hi"。指定 localhost/Test/Monster/hi/hello 失败并给出 404.

很抱歉,但正如你所说

localhost/Test/Monster/Hi

工作意味着只配置了一个参数路由...您是否尝试过重新启动 IISExpress,因为路由在第一次调用时加载并且仅加载一次..

更改路由后,您必须从图标托盘中停止 IIS Express 并重新运行 您投影然后使用一个参数它应该抛出错误..因为您没有设置这些选项它仅当您同时指定这两个参数时才会起作用。

试试这个:

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

        routes.MapRoute(
          name: "Servers",
          url: "{controller}/{action}/{id}/{a}",
          defaults: new
          {
            controller = "Test",
            id = UrlParameter.Optional,
            a = UrlParameter.Optional 
          }
        );
    }

另外,这是你唯一的路线吗?
路由设置的顺序很重要,很容易用后面的路由覆盖路由。这个错误我已经犯过无数次了。

如果操作不是可选的,您应该为其指定默认值。请尝试:

routes.MapRoute(
          name: "Servers",
          url: "{controller}/{action}/{id}/{a}",
          defaults: new
          {
            controller = "Test",
            action = "Monster"
          }
        );

在您的方法中,您指定了参数字符串 a,因此当您传递 URl localhost/Test/Monster/hi/hello MVC 将在 url 中查找参数 a,因为它匹配 post参数与函数中的参数

所以这个 link 可能会像帮助我一样帮助你

http://www.codeproject.com/Articles/299531/Custom-routes-for-MVC-Application

这是一个非常晚的响应,但问题是下游有一个正在注册的区域导致了路由问题。正在注册的区域有一个可选的 url 参数,该参数正在接管路线。使用这个注册区域解决了这个问题。