路由

创建路由

    路由提供了Route类作为IRouter的标准实现。当调用RouteAsync方法时,Route使用路由模板语法定义匹配URL路径的模式,当调用GetVirtualPath方法时,Route会使用相同的路由模板生成URL。

    大多数应用会通过调用MapRoute方法或定义在IRouteBuilder接口上的一个类似扩展方法来创建路由

    下面是两个典型的ASP.NET。MVC路由例子

routes.MapRoute(
    name: "default_route",
    template: "{controller}/{action}/{id?}",
    defaults: new { controller = "Home", action = "Index" });

routes.MapRoute(
    name: "default_route",
    template: "{controller=Home}/{action=Index}/{id?}");

使用路由中间件

    在使用路由前,需要添加依赖项 microsoft.aspnetcore.routing

   在Staup中添加路由到服务容器

public void ConfigureServices(IServiceCollection services)
{
       //添加路由服务
       services.AddRouting();
}

   路由必须在Startup类Configure方法中配置

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
           var trackPackageRouteHandler = new RouteHandler(context =>
             {
                 var routeVal = context.GetRouteData().Values;
                 return context.Response.WriteAsync($"Hello! Route values: {string.Join(", ", routeVal)}");
             });
            var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler);
            routeBuilder.MapRoute(
                 "Track Package Route",
                  "package/{operation:regex(^track|create|detonate$)}/{id:int}"
             );
//只允许Get请求 routeBuilder.MapGet("hello/{name}.{ext?}", context => { var name = context.GetRouteValue("name"); var ext = context.GetRouteValue("ext"); return context.Response.WriteAsync($"Hi,{name}.{ext}!"); }); var routes = routeBuilder.Build(); app.UseRouter(routes); }

 响应列表

URIResponse
/package/create/3 Hello! Route values: [operation, create], [id, 3]
/package/track/-3 Hello! Route values: [operation, track], [id, -3]
/package/track/-3/ Hello! Route values: [operation, track], [id, -3]
/package/track/ <未通过,没有匹配>
GET /hello/Joe Hi, Joe!
POST /hello/Joe <未通过, 只匹配GET请求>
GET /hello/Joe/Smith <未通过,没有匹配>

   框架提供了一系列的创建路由扩展方法

  • MapRoute
  • MapGet
  • MapPost
  • MapPut
  • MapDelete
  • MapVerb        

路由约束

约束示例匹配示例注释
int {id:int} 123 匹配所有整型
bool {active:bool} true 匹配 true 或 false
datetime {dob:datetime} 2016-01-01 匹配一个合法的 DateTime 值 (固定区域性 - 请看 options)
decimal {price:decimal} 49.99 匹配一个合法的 decimal 值
double {weight:double} 4.234 匹配一个合法的 double 值
float {weight:float} 3.14 匹配一个合法的 float 值
guid {id:guid} 7342570B- 匹配一个合法的 Guid 值
long {ticks:long} 123456789 匹配一个合法的 long 值
minlength(value) {username:minlength(5)} steve 至少5个字符串长。
maxlength(value) {filename:maxlength(8)} somefile 字符串不能超过8个字符长。
length(min,max) {filename:length(4,16)} Somefile.txt 字符串至少8个长度且不超过16个字符长度。
min(value) {age:min(18)} 19 值至少是18。
max(value) {age:max(120)} 91 值不能超过120。
range(min,max) {age:range(18,120)} 91 值必须介于18和120之间。
alpha {name:alpha} Steve 字符串必须是由字母字符组成。
regex(expression) {ssn:regex(^d{3}-d{2}-d{4}$)} 123-45-6789 字符串必须匹配提供的正则表达式。
required {name:required} Steve 用于在URL生成时强制必须存在值。

      验证URL可转为CLR类型(例如Int或DateTime)的路由约束总是使用固定区域性;它们认为URL是不可本地化的,框架提供的路由约束不会修改路由值,从URL解析过来的所有路由值都会存为字符串。例如,浮点路由约束会试图将路由值转换为一个浮点性,但转换后的值只用于验证它是否能够转换为浮点型

原文地址:https://www.cnblogs.com/yan7/p/7837650.html