让我们看看在 RouteConfig.cs 中映射的这两条路由,一条有 guid,一条没有:
// Non-guid route
routes.MapPageRoute(
name: null,
url: "dashboard/{action}",
defaults: new { controller = "Dashboard", action = "Index" }
);
// Guid route
routes.MapPageRoute(
name: null,
url: "{guid}/dashboard/{action}",
defaults: new { controller = "Dashboard", action = "Index" }
);
方法调用:
UrlHelper.Action("Index", "Dashboard", new { guid = "c73b47b9-4ad5-414a-a92e-8937231f8e2bD" })
该方法返回:
"/dashboard/?guid=c73b47b9-4ad5-414a-a92e-8937231f8e2b"
但我期待的是:
"/c73b47b9-4ad5-414a-a92e-8937231f8e2b/dashboard/"
请注意,它将 guid 作为查询字符串值而不是第一个参数。
现在,如果我对第二个 url 进行硬编码,应用程序将使用正确的 guid 路由,并且如果我改用路由名称 (UrlHelper.RouteUrl) 也可以正常工作,所以我认为这不是路由映射本身的问题。这些解决方案都不适合我们的应用程序,因为我们有数百条路线,并且目前到处都在使用 UrlHelper.Action。
我还尝试了几乎所有 UrlHelper.Action 的重载和变体,包括传递 RouteValueDictionary 而不是匿名对象。
这是一个 ASP.NET MVC 4 网络应用程序。
关于为什么这不起作用的任何想法? (或替代方案,可能使用一条路线)
最佳答案
尝试这个。把更具体的路线放在第一位:
routes.MapRoute(
name: "WithGUID",
url: "{guid}/dashboard/{action}",
defaults: new { controller = "Dashboard", action = "Index" }
);
routes.MapRoute(
name: "NoGUID",
url: "dashboard/{action}",
defaults: new { controller = "Dashboard", action = "Index", guid = "" }
);
关于c# - UrlHelper.Action 方法未映射到具有第一个可变参数的正确路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25084592/