萨拉姆
我一直在尝试使用多个MapRoute
,但没有成功。我的场景是,我正在进行一个项目,用户创建配置文件,然后显示配置文件的公共预览。
到目前为止,对于公共配置文件,我使用默认的id
示例:
https://localhost:44300/Profile/DoctorProfile/alijamal14
这里的"Profile"是{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并制作确保拼写正确。
请求的URL:/alijamal14
版本信息:Microsoft.NET Framework版本:4.0.30319;ASP.NET版本:4.6.1055.0
如果我注释掉第一个MapRoute代码localhost:44300/Profile/DoctorProfile/alijamal14工作,但其他控制器和操作停止工作
如何在网站domanname链接后实现用户名以及默认路由功能?
感谢
您可以使用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){
......
}
}