Using URL Routing
Contents
The IEndpointRouteBuilder Extension Methods
Name | Description |
---|---|
MapGet(pattern,endpoint) | routes HTTP GET requests that match the URL pattern to the endpoint |
MapPost(pattern,endpoint) | This method routes HTTP POST requests that match the URL pattern to the endpoint |
MapPut(pattern,endpoint) | routes HTTP PUT requests that match the URL pattern to the endpoint |
MapDelete(pattern,endpoint) | routes HTTP DELETE requests that match the URL pattern to the endpoint |
MapMethods(pattern,methods,endpoint | routes requests made with one of the specified HTTP methods that match the URL pattern to the endpoint |
Map(pattern,endpoint) | routes all HTTP requests that match the URL pattern to the endpoint |
添加路由中间件和定义一个endpoint
- UseRouting方法添加中间件来响应管道中的请求
- UseEndpoint方法使用端点来匹配URL
路由方式
app.UseEndpoints
app.UseEndpoints(endpoints=>{endpoints.MapGet("routing",async context=>{
await context.Response.WriteAsync("Request Was Routed");
})})
使用中间件
app.UseEndpoints(endpoints=>{
endpoints.MapGet("capital/uk",new Capital().Invoke);
});
简化的管道配置
WebApplication类实现了IEndpointRoutedBuilder接口,可以更简洁的创建接口
app.MapGet("capital/uk",new Capital().Invoke);
在URL模式中使用段变量
app.MapGet("{first}/{second}/{third}",async context=>{
await context.Response.WriteAsync("Request Was Routed\n");
foreach(var kvp in context.Request.RouteValues)
{
await context.Response.WriteAsync($"{kvp.Key}:{kvp.Value}\n");
}
})
从路由生成URL
app.MapGet("population/{city}",Population.Endpoint).WithMetaata(new RouteNameMetadata("population"));
为字段变量使用默认值
app.MapGet("capital/{contry=France}",Capital.Endpoint);
在URL模式中使用可选字段
需要在中间件中设置值
app.MapGet("size/{city?}",Population.Endpoint);
使用catchall字段变量
app.MapGet("{first}/{second}/{*catchall}");
约束字段匹配
app.MapGet("{first:int}/{second:bool}",async context=>{
});
约束匹配到一组特定的值
app.MapGet("capital/{country:regx(^uk|france|monaco$)}",capital.Endpoint);
定义Fallback路由
app.MapFallback(async context=>{
await context.Response.WriteAsync("Routed to fallback endpoint");
})
高级路由属性
创建自定义约束
需要自己将建继承自IRouteConstraint类,实现Match方法
Filed under: ASP.NET Core,C#,编程 - @ 2022年4月19日 上午9:59