所以我有一個HomeController
,要訪問它與Actions
我必須鍵入url.com/home/action。更改ASP.NET核心中的控制器路由
是否有可能將此更改爲其他類似url.com/anothernamethatpointsthomeactually/action?
所以我有一個HomeController
,要訪問它與Actions
我必須鍵入url.com/home/action。更改ASP.NET核心中的控制器路由
是否有可能將此更改爲其他類似url.com/anothernamethatpointsthomeactually/action?
您可以通過修改你的路由配置更改您的網址。 它有點像htaccess,但不是真的。 https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/creating-custom-routes-cs
另一種解決方案是創建頁面並執行服務器重定向。
Server.Transfer
在控制器的頂部使用Route屬性將允許您在整個控制器上定義路徑。 [Route("anothernamethatpointstohomeactually")]
您可以閱讀更多here。
您可以app.UseMvc(routes =>
塊內的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沒有核心MVC)
您還可以通過routes.MapRoute
在RouteConfig
添加新Route
:
routes.MapRoute(
name: "SomeDescriptiveName",
url: "AnotherNameThatPointsToHome/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
確保,你插入在您定義您的Default
路線之前的代碼。
欲瞭解更多信息,請訪問docs。
我建議你使用屬性的路由,當然這取決於您的方案。
[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/name
[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.