DotNETCore 学习笔记 路由

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

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


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


routes.MapRoute(
  name: "blog",
  template: "Blog/{*article}",
  defaults: new { controller = "Blog", action = "ReadArticle" });

routes.MapRoute(
    name: "us_english_products",
    template: "en-US/Products/{id}",
    defaults: new { controller = "Products", action = "Details" },
    constraints: new { id = new IntRouteConstraint() },
    dataTokens: new { locale = "en-US" });


Using Routing Middleware

To use routing middleware, add it to the dependencies in project.json:
"Microsoft.AspNetCore.Routing": <current version>


public void ConfigureServices(IServiceCollection services)
{
    services.AddRouting();
}


public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    var trackPackageRouteHandler = new RouteHandler(context =>
    {
        var routeValues = context.GetRouteData().Values;
        return context.Response.WriteAsync(
            $"Hello! Route values: {string.Join(", ", routeValues)}");
    });

    var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler);

    routeBuilder.MapRoute(
        "Track Package Route",
        "package/{operation:regex(^track|create|detonate$)}/{id:int}");

    routeBuilder.MapGet("hello/{name}", context =>
    {
        var name = context.GetRouteValue("name");
        // This is the route handler when HTTP GET "hello/<anything>"  matches
        // To match HTTP GET "hello/<anything>/<anything>, 
        // use routeBuilder.MapGet("hello/{*name}"
        return context.Response.WriteAsync($"Hi, {name}!");
    });            

    var routes = routeBuilder.Build();
    app.UseRouter(routes);


URI                            Response
/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/                     <Fall through, no match> 
GET /hello/Joe                         Hi, Joe! 
POST /hello/Joe                     <Fall through, matches HTTP GET only> 
GET /hello/Joe/Smith                     <Fall through, no match> 


The framework provides a set of extension methods for creating routes such as:
•MapRoute
•MapGet
•MapPost
•MapPut
•MapDelete
•MapVerb


Route Constraint 

constraint    Example        Example Match        Notes
int         {id:int}     123             Matches any integer 
bool         {active:bool}     true             Matches true or false 
datetime     {dob:datetime}     2016-01-01         Matches a valid DateTime value 
decimal     {price:decimal} 49.99             Matches a valid decimal value 
double         {weight:double} 4.234             Matches a valid double value 
float         {weight:float}     3.14             Matches a valid float value 
guid         {id:guid}     7342570B-<snip>     Matches a valid Guid value 
long         {ticks:long}     123456789         Matches a valid long value 
minlength(value) {username:minlength(5)} steve         String must be at least 5 characters long. 
maxlength(value) {filename:maxlength(8)} somefile     String must be no more than 8 characters long. 
length(min,max) {filename:length(4,16)} Somefile.txt     String must be at least 8 and no more than 16
min(value)     {age:min(18)}     19             Value must be at least 18. 
max(value)     {age:max(120)}     91             Value must be no more than 120. 
range(min,max)     {age:range(18,120)} 91             Value must be at least 18 but no more than 120. 
alpha         {name:alpha}     Steve             String must consist of alphabetical characters. 
regex(expression){ssn:regex(^d{3}-d{2}-d{4}$)} 123-45-6789 ***
required     {name:required} Steve             ***


URL Generation :
app.Run(async (context) =>
{
    var dictionary = new RouteValueDictionary
    {
        { "operation", "create" },
        { "id", 123}
    };

    var vpc = new VirtualPathContext(context, null, dictionary, "Track Package Route");
    var path = routes.GetVirtualPath(vpc).VirtualPath;

    context.Response.ContentType = "text/html";
    await context.Response.WriteAsync("Menu<hr/>");
    await context.Response.WriteAsync($"<a href='{path}'>Create Package 123</a><br/>");
});


routes.MapRoute("blog_route", "blog/{*slug}",
  defaults: new { controller = "Blog", action = "ReadPost" });
原文地址:https://www.cnblogs.com/ziranquliu/p/5871141.html