首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >过载动作的MapRoute

过载动作的MapRoute
EN

Stack Overflow用户
提问于 2012-12-27 13:11:06
回答 1查看 1.5K关注 0票数 4

我有一个财务总监:

代码语言:javascript
复制
public class ProfileController : Controller
{
    public ActionResult Index( long? userkey )
    {
        ...
    }

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

如何为此操作定义MapRoute,工作方式如下:

mysite.com/Profile/8293378324043043840

这必须是第一个行动

mysite.com/Profile/MyUserName

这必须转到第二步

我有这条第一步的路线

代码语言:javascript
复制
routes.MapRoute( name: "Profile" , url: "Profile/{userkey}" , defaults: new { controller = "Profile" , action = "Index" } );

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-27 13:27:10

首先,如果您使用相同的Http谓词(在您的示例中是GET),则不能重载控制器操作,因为您需要有唯一的操作名称。

因此,您需要将您的行为命名为不同的:

代码语言:javascript
复制
public class ProfileController : Controller
{
    public ActionResult IndexKey( long? userkey )
    {
        ...
    }

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

或者您可以使用ActionNameAttribute为您的操作指定不同的名称:

代码语言:javascript
复制
public class ProfileController : Controller
{
    [ActionName("IndexKey")]
    public ActionResult Index( long? userkey )
    {
        ...
    }

    [ActionName("IndexName")]
    public ActionResult Index( string username )
    {
        ...
    }
}

然后,您将需要使用using route constraintsuserkey上的两条路由作为一个数值来设置您的操作:

代码语言:javascript
复制
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"});
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14055294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档