设置自定义路由只能在asp.net Web表单中形成一些页面

时间:2017-12-06 08:49:03

标签: c# asp.net routing global-asax

我使用asp.net webforms创建了一个网站。它使用url友好的默认路由。我可以通过将其分配给global.asax而不影响所有其他页面路由来为某些页面设置自定义路由吗?

1 个答案:

答案 0 :(得分:0)

默认情况下,MVC使用使用此类内容的传统路由。

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

转换为http://localhost:9999/<controllerName>/<ActionName>/<OptionalIDs>

但是,如果您希望在ASP.NET MVC 5中实现自定义路由,则此功能称为属性路由,如果您使用的是Visual Studio 2015或更高版本。

例如:

将以下行添加到global.asax.cs文件中将启用MVC 5应用程序中的属性路由: routes.MapMvcAttributeRoutes();

这将呈现为http://localhost:9999

[HttpGet]
[Route(Name = "HomeView")]
public ActionResult Index()
{
  return View();
}

这将呈现为http://localhost:9999/Login

[HttpGet]
[Route("~/Login", Name = "LoginGET")]
public ActionResult Login()
{
   return View();
}

在您的视图中,您可以使用Html.BeginRouteForm("<RouteName>", FormMethod.Post)辅助方法处理路线。

[HttpPost]
[Route("~/Login", Name = "LoginPOST")]
public ActionResult Login(FormCollection UserCredentials)
{
   //do stuff
   return RedirectToRoute("HomeView");
}

要通过_layout.html中的路由引用MVC操作,您可以使用:

Html.RouteLink("Link text that you want to display in the view", "<RouteName>");

有关详情,请随时查看MSDN Attribute Routing

相关问题