1、默认路由的配置和使用
ASP.NET Core中是使用Startup
类中ConfigureServices()
方法中配置默认路由:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
比较新的版本中可以在Program.cs
文件中配置,在Program.cs
文件的结构与之前的版本有所不同,采用了更简化的形式。配置如下,
var builder = WebApplication.CreateBuilder(args); // 添加服务到容器 builder.Services.AddControllersWithViews(); var app = builder.Build(); // 配置 HTTP 请求管道 if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); // 配置默认路由 app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
也可以这样配置:
routes.MapRoute(
name: "default_route",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" }
);
2、配置多个默认路由
上面配置默认路由后,可能有特定的需求,这时就需要配置多个默认路由:
app.UseMvc(routes =>
{
//New Route
routes.MapRoute(
name: "about-route",
template: "about",
defaults: new { controller = "Home", action = "About" }
);
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
3、配置标签(Attributes)为个方法或控制器指定路由
可以在方法或控制器上设置标签来指定路由:
[Route("[controller]")]
public class AnalyticsController : Controller
{
[Route("Dashboard")]
public IActionResult Index()
{
return View();
}
[Route("[action]")]
public IActionResult Charts()
{
return View();
}
}
在本示例中,我们可以通过以下路径访问控制器方法:
/Analytics/Dashboard
/Analytics/Charts
4、配置RESTful路由
声明一个RESTful控制器,需要使用以下路由配置:
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] {"hello", "world!"};
}
// POST api/values
[HttpPost]
public void PostCreate([FromBody] string value)
{
}
// POST api/values/5
[HttpPost("{id}")]
public void PostUpdate(int id, [FromBody] string value)
{
}
}
5、配置路由器参数约束
可以对路由中配置参数的类型进行约束:
[HttpGet("{id:int}")]
public string GetById(int id)
{
return "item " + id;
}
也可以在默认路由中配置参数约束:
routes.MapRoute(
name: "getProductById",
template: "Products/{id:int}",
defaults: new { controller = "Products", action = "GetById" });