出于SEO和SEM的原因,我被要求在我们的MVC ASP.NET应用程序中实现以下URL:
/colour/{colour1}/[{colour2}]/[{colour3}]/[{colour4}]/fill
在所有情况下,网址都需要以 / color 开头,并以 / fill 结尾。至少会有colour1和另外三种颜色({colour2..4}),所以以下所有颜色都是有效的:
/colour/red/fill
/colour/red/blue/fill
/colour/red/blue/green/fill
/colour/red/blue/green/yellow/fill
/colour/yellow/blue/green/red/fill
以下不起作用:
aRoutes.MapRoute("Blah", "colour/{colour1}/{colour2}/{colour3}/{colour4}/fills", new
{
controller = "MyController",
action = "MyAction",
colour2 = UrlParameter.Optional,
colour3 = UrlParameter.Optional,
colour4 = UrlParameter.Optional
});
[HttpGet]
public virtual ActionResult MyAction(string colour1, string colour2 = "", string colour3 = "", string colour4 = "")
{
return null;
}
,两者都没有:
aRoutes.MapRoute("Blah", "colour/{*colour}/fills", new
{
controller = "MyController",
action = "MyAction2",
});
因为尾随/填充会导致问题。
所以我的问题是:
答案 0 :(得分:0)
Catch-All需要是列表中的最后一个参数。
如果在catch-all之后有/ fill,Visual Studio将抛出以下错误:
An exception of type 'System.ArgumentException' occurred in
Microsoft.AspNet.Routing.dll but was not handled in user code
Additional information: A catch-all parameter can only appear as the
last segment of the route template.
最简单的解决方案是将/ fill移动到catch-all之前,如果它是静态的。如果/ fill是颜色的动作,也许使用/ colourAction / {colourAction}将动作拉到控制器中的函数?
https://msdn.microsoft.com/en-us/library/cc668201.aspx#Anchor_5
答案 1 :(得分:0)
我能够实现的解决方案需要声明额外的路由,这些路由都指向同一个方法。一定要按参数个数的顺序按顺序声明它们(所以全部4个,最后一个):
aRoutes.MapRoute("Blah", "colour/{colour1}/{colour2}/{colour3}/{colour4}/fills", new
{
controller = "MyController",
action = "MyAction",
});
aRoutes.MapRoute("Blah", "colour/{colour1}/{colour2}/{colour3}/fills", new
{
controller = "MyController",
action = "MyAction",
});
aRoutes.MapRoute("Blah", "colour/{colour1}/{colour2}/fills", new
{
controller = "MyController",
action = "MyAction",
});
aRoutes.MapRoute("Blah", "colour/{colour1}/fills", new
{
controller = "MyController",
action = "MyAction",
});
,控制器方法如下:
public virtual ActionResult MyAction(string colour1, string colour2 = "", string colour3 = "", string colour4 = "")
{
return null;
}
最终不是一个很好的解决方案,因为如果我们想添加colour5那么我们需要修改路由表和操作方法。但这就是在这种情况下cookie崩溃的方式。