我正在尝试为我的 Web 应用程序的一个操作创建路由,但我无法这样做。这是当前的网址: http://localhost:8093/Profile/Get?Name=John我想更改为 http://localhost:8093/Profile/John
在我的路由配置中,我尝试过
routes.MapRoute(
name: "Profile",
url: "Profile/Get/{Name}",
defaults: new { controller = "Profile", action = "Get", Name = UrlParameter.Optional }
);
和
routes.MapRoute(
name: "Profile",
url: "Profile/{Name}",
defaults: new { controller = "Profile", action = "Get", Name = UrlParameter.Optional }
);
但没有任何效果。需要一些关于我做错了什么的指导。
这是注册路由方法
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Unauthorized",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Unauthorized", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "PageNotFound",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "PageNotFound", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "InternalServerError",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "InternalServerError", id = UrlParameter.Optional }
);
}
routes.MapRoute(
name: "Profile",
url: "Profile/{Name}",
defaults: new { controller = "Profile", action = "Get", Name = UrlParameter.Optional }
);
您可以使用这个并更改自定义控制器名称和操作名称:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional }
);
无需在 URL 设置中使用查询字符串。
你的问题是default
路线,它应该总是在最后。RouteConfig.cs
文件从上到下读取,并将转到它找到与 URL 匹配的第一个路由。请将您的RouteConfig.cs
更改为下面给出的。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Profile",
url: "Profile/{Name}",
defaults: new { controller = "Profile", action = "Get", Name = UrlParameter.Optional }
);
routes.MapRoute(
name: "Unauthorized",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Unauthorized", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "PageNotFound",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "PageNotFound", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "InternalServerError",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "InternalServerError", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}