Rai*_*ika 4 asp.net-mvc-routing asp.net-mvc-4
我有这个控制器:
public class ProfileController : Controller
{
public ActionResult Index( long? userkey )
{
...
}
public ActionResult Index( string username )
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
如何为此操作定义MapRoute,如下所示:
mysite.com/Profile/8293378324043043840
这必须先行动
mysite.com/Profile/MyUserName
这必须要进行第二次行动
我有这条路线进行第一次行动
routes.MapRoute( name: "Profile" , url: "Profile/{userkey}" , defaults: new { controller = "Profile" , action = "Index" } );
Run Code Online (Sandbox Code Playgroud)
我需要添加另一个MapRoute吗?或者我可以为这两个动作更改当前的MapRoute吗?
首先,如果您使用相同的Http Verb(在您的情况下为GET),则不能重载控制器操作,因为您需要具有唯一的操作名称.
所以你需要以不同的方式命名你的行为:
public class ProfileController : Controller
{
public ActionResult IndexKey( long? userkey )
{
...
}
public ActionResult IndexName( string username )
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用它ActionNameAttribute为您的操作指定不同的名称:
public class ProfileController : Controller
{
[ActionName("IndexKey")]
public ActionResult Index( long? userkey )
{
...
}
[ActionName("IndexName")]
public ActionResult Index( string username )
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
然后,你将需要两个路由使用路由约束的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"});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1462 次 |
| 最近记录: |