Bootstrap
本文主要介绍ASP.NET Core 路由(router)配置和使用方法,.NET Core中MVC的路由的使用方法,和之前asp.net mvc中配置使用有些区别,但也不是很大。下面看一下具体配置使用方法。

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?}");
});
}
}

也可以这样配置

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" });

参考文档https://stormpath.com/blog/routing-in-asp-net-core