ASP.NET Core 中可以使用路由属性来定义 Controller 中的 Action 的路由,以便在应用程序中确定 URL。将 RouteAttribute 应用在 Action 上,可以指定 URL 模板,例如:
public class HomeController : Controller
{
[Route("/")]
public IActionResult Index()
{
return View();
}
[Route("/About")]
public IActionResult About()
{
return View();
}
[Route("/Contact/{id}")]
public IActionResult Contact(int id)
{
return View(id);
}
}
在上述示例中,第一个 Action 总是响应应用程序的根 URL。第二个 Action 响应 /About URL,第三个 Action 响应 /Contact/{id} URL。
在应用程序启动时,可以使用 UseEndpoints 方法来注册路由,例如:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
此示例中,使用 MapControllerRoute 方法与默认值(名为默认值的控制器和 Action)来设置默认路由。
使用路由属性路由,可以更灵活地定义应用程序的 URL。注意,路由属性也支持模板参数,因此可以轻松地定义具有可变部分的 URL,例如 /Contact/{id}。