【发布时间】:2018-01-30 01:37:02
【问题描述】:
所以我有一个HomeController,要与Actions 一起访问它,我必须输入url.com/home/action。
是否可以将其更改为 url.com/anothernamethatpointstohomeactually/action 之类的其他名称?
【问题讨论】:
标签: c# asp.net-core routing asp.net-core-mvc
所以我有一个HomeController,要与Actions 一起访问它,我必须输入url.com/home/action。
是否可以将其更改为 url.com/anothernamethatpointstohomeactually/action 之类的其他名称?
【问题讨论】:
标签: c# asp.net-core routing asp.net-core-mvc
我建议你使用属性路由,当然这取决于你的场景。
[Route("prefix")]
public class Home : Controller {
[HttpGet("name")]
public IActionResult Index() {
}
}
这将在url.com/prefix/name 找到
属性路由有很多选项,一些示例:
[Route("[controller]")] // there are placeholders for common patterns
as [area], [controller], [action], etc.
[HttpGet("")] // empty is valid. url.com/prefix
[Route("")] // empty is valid. url.com/
[HttpGet("/otherprefix/name")] // starting with / won't use the route prefix
[HttpGet("name/{id}")]
public IActionResult Index(int id){ ... // id will bind from route param.
[HttpGet("{id:int:required}")] // you can add some simple matching rules too.
【讨论】:
使用控制器顶部的 Route 属性将允许您在整个控制器上定义路由。
[Route("anothernamethatpointstohomeactually")]
您可以阅读更多here。
【讨论】:
您可以在 Startup.Configure 块内的 Startup.Configure 方法中添加新的 Routes:
routes.MapRoute(
name: "SomeDescriptiveName",
template: "AnotherNameThatPointsToHome/{action=Index}/{id?}",
defaults: new { controller = "Home"}
);
代码与 ASP.NET MVC 非常相似。
有关详细信息,请参阅Routing in ASP.NET Core。
下面是 ASP.NET MVC(不是 ASP.NET Core MVC)
您还可以通过routes.MapRoute 在您的RouteConfig 中添加新的Route:
routes.MapRoute(
name: "SomeDescriptiveName",
url: "AnotherNameThatPointsToHome/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
确保在定义 Default 路由之前插入代码。
欲了解更多信息,请访问docs。
【讨论】:
您可以通过修改路由配置来更改您的网址。 它有点像 htaccess,但不是真的。 https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/creating-custom-routes-cs
另一种解决方案是创建一个页面并进行服务器重定向。
Server.Transfer
【讨论】: