我有这个 Controller :
public class ProfileController : Controller
{
public ActionResult Index( long? userkey )
{
...
}
public ActionResult Index( string username )
{
...
}
}
我如何为这个 Action 定义 MapRoute,像这样工作:
mysite.com/Profile/8293378324043043840
这必须是第一个行动
mysite.com/Profile/MyUserName
这必须转到第二个 Action
我有第一次行动的路线
routes.MapRoute( name: "Profile" , url: "Profile/{userkey}" , defaults: new { controller = "Profile" , action = "Index" } );
我需要添加另一个 MapRoute 吗?或者我可以更改这两个操作的当前 MapRoute 吗?
最佳答案
首先,如果您使用相同的 Http 动词(在您的情况下为 GET),则不能重载 Controller 操作,因为您需要具有唯一的操作名称。
因此,您需要以不同的方式命名您的操作:
public class ProfileController : Controller
{
public ActionResult IndexKey( long? userkey )
{
...
}
public ActionResult IndexName( string username )
{
...
}
}
或者您可以使用
ActionNameAttribute
为您的操作赋予不同的名称:public class ProfileController : Controller
{
[ActionName("IndexKey")]
public ActionResult Index( long? userkey )
{
...
}
[ActionName("IndexName")]
public ActionResult Index( string username )
{
...
}
}
那么你将需要两条路线 using route constraints在
userkey
是一个数值来设置您的操作:routes.MapRoute(name: "Profile", url: "Profile/{userkey}",
defaults: new { controller = "Profile", action = "IndexKey" },
constraints: new { userkey = @"\d*"});
routes.MapRoute(name: "ProfileName", url: "Profile/{userName}",
defaults: new {controller = "Profile", action = "IndexName"});
关于asp.net-mvc-4 - 用于重载操作的 MapRoute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14055294/