MapRoute用于重载Action

时间:2012-12-27 13:11:07

标签: asp.net-mvc-4 asp.net-mvc-routing

我有这个控制器:

public class ProfileController : Controller
{
    public ActionResult Index( long? userkey )
    {
        ...
    }

    public ActionResult Index( string username )
    {
        ...
    }
}

如何为此操作定义MapRoute,如下所示:

  

mysite.com/Profile/8293378324043043840

这必须先行动

  

mysite.com/Profile/MyUserName

这必须转到第二个动作

我有第一个行动的路线

routes.MapRoute( name: "Profile" , url: "Profile/{userkey}" , defaults: new { controller = "Profile" , action = "Index" } );

我需要添加另一个MapRoute吗?或者我可以为这两个动作更改当前的MapRoute吗?

1 个答案:

答案 0 :(得分:6)

首先,如果您使用相同的Http Verb(在您的情况下为GET),则不能重载控制器操作,因为您需要具有唯一的操作名称。

所以你需要以不同的方式命名你的行为:

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 )
    {
        ...
    }
}

然后,您需要在userkey上使用using route constraints的两条路线作为数字值来设置您的操作:

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"});
相关问题