加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-4 – MapRoute for overload Action

发布时间:2020-12-16 06:48:22 所属栏目:asp.Net 来源:网络整理
导读:我有这个控制器: public class ProfileController : Controller{ public ActionResult Index( long? userkey ) { ... } public ActionResult Index( string username ) { ... }} 如何为此操作定义MapRoute,如下所示: mysite.com/Profile/82933783240430438
我有这个控制器:

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吗?

解决方法

首先,如果您使用相同的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",action = "IndexKey" },constraints: new { userkey = @"d*"});

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读