asp.net-mvc-4 - 用于重载操作的 MapRoute

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

我有这个 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 constraintsuserkey是一个数值来设置您的操作:
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/

相关文章:

asp.net-mvc - ASP.NET MVC切换语言,如何实现?

asp.net-mvc - 带空格的类别的 MVC 路由

c# - ASP.NET 路由,其中​​两个 Controller 操作具有相同数量的参数

asp.net-mvc - 在 MVC 中生成绝对 Url 时出现问题

javascript - AJAX:异步将文件发布到服务器

c# - 在Azure服务器中每天自动调用一次API

c# - 布局页面中的 asp.net mvc 登录表单(未找到部分 View 'LogIn')

jquery - 需要完成三个文本字段之一,验证不适用于强 View

asp.net-mvc - asp.net mvc url 操作忽略旧参数值

c# - 使用属性路由时如何获取 Mvc 5 Controller 的 ActionDescriptor?