【问题标题】:Username Mutiple MapRoute Not Working用户名多个地图路线不起作用
【发布时间】:2016-05-10 18:29:55
【问题描述】:

萨拉姆

我一直在尝试使用多个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。您正在寻找的资源(或其之一 依赖项)可能已被删除,名称已更改,或者是 暂时不可用。请查看以下 URL 并制作 确保拼写正确。

请求的网址:/alijamal14

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

如果我先注释掉 MapRoute 代码 localhost:44300/Profile/DoctorProfile/alijamal14 工作,但其他控制器和操作停止工作

如何在网站域名链接后获得用户名以及默认路由功能?

谢谢

【问题讨论】:

  • 你不能(你可以交换路线的顺序来制作https://localhost:44300/alijamal14,但没有其他办法了)。你需要让路线可识别

标签: c# asp.net-mvc


【解决方案1】:

您可以使用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){
     ......
    }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 2013-05-03
    相关资源
    最近更新 更多