用户名多个MapRoute不起作用

时间:2016-05-10 08:57:00

标签: c# asp.net-mvc

达累斯萨拉姆

我一直在尝试使用多个MapRoute,但我没有成功。我的场景是这个我正在开发一个项目,用户创建个人资料,然后显示个人资料的公开预览。

到目前为止公开个人资料我使用默认id 示例:

  

https://localhost:44300/Profile/DoctorProfile/alijamal14

此处'个人资料'为{controller},'DoctorProfile'为{action},'alijamal14'为{id},这完美无缺

我希望实现一个用户名路由,即使没有提及控制器和操作

,也会有相同的效果
  

https://localhost:44300/alijamal14

有关下面的详细信息,我提到了我的Rout.Config.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace DoctorSearchEngine
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Doctor", action = "Search", id = UrlParameter.Optional },
                namespaces: new[] { "DoctorSearchEngine.Controllers" }
            );

            routes.MapRoute(
                name: "Users",
                url: "{username}",
                defaults: new { controller = "Profile", action = "DoctorProfile", username = UrlParameter.Optional },
                namespaces: new[] { "DoctorSearchEngine.Controllers" }
            );
        }
    }
}

我收到此错误

  应用程序中的服务器错误。

     

无法找到资源。

     

描述:HTTP 404.您正在寻找的资源(或其中一个   依赖项)可能已被删除,其名称已更改,或者是   暂时不可用。请查看以下网址并制作   确保它拼写正确。

     

请求的网址:/ alijamal14

     

版本信息:Microsoft .NET Framework版本:4.0.30319;   ASP.NET版本:4.6.1055.0

如果我先注释掉MapRoute Code localhost:44300 / Profile / DoctorProfile / alijamal14有效但其他控制器和动作停止工作

如何在网站domanname链接和默认路由功能之后实现用户名?

由于

1 个答案:

答案 0 :(得分:2)

您可以使用Attribute Routing将URL参数配置移动到控制器。

启用属性路由:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Doctor", action = "Search", id = UrlParameter.Optional },
            namespaces: new[] { "DoctorSearchEngine.Controllers" }
        );

    }

现在,你可以使用这样的属性:

public class ProfileController : Controller
{      
    [Route("{username}")]
    public ActionResult DoctorProfile(string username){
     ......
    }
 }