1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Constraints;
using Microsoft.Extensions.DependencyInjection;
namespace RoutingWebSite
{
public class UseRouterStartup
{
private static readonly TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(10);
public void ConfigureServices(IServiceCollection services)
{
services.AddRouting();
}
public void Configure(IApplicationBuilder app)
{
app.UseRouter(routes =>
{
routes.DefaultHandler = new RouteHandler((httpContext) =>
{
var request = httpContext.Request;
return httpContext.Response.WriteAsync($"Verb = {request.Method.ToUpperInvariant()} - Path = {request.Path} - Route values - {string.Join(", ", httpContext.GetRouteData().Values)}");
});
routes.MapGet("api/get/{id}", (request, response, routeData) => response.WriteAsync($"API Get {routeData.Values["id"]}"))
.MapMiddlewareRoute("api/middleware", (appBuilder) => appBuilder.Run(httpContext => httpContext.Response.WriteAsync("Middleware!")))
.MapRoute(
name: "AllVerbs",
template: "api/all/{name}/{lastName?}",
defaults: new { lastName = "Doe" },
constraints: new { lastName = new RegexRouteConstraint(new Regex("[a-zA-Z]{3}", RegexOptions.CultureInvariant, RegexMatchTimeout)) });
});
app.Map("/Branch1", branch => SetupBranch(branch, "Branch1"));
app.Map("/Branch2", branch => SetupBranch(branch, "Branch2"));
}
private void SetupBranch(IApplicationBuilder app, string name)
{
app.UseRouter(routes =>
{
routes.MapGet("api/get/{id}", (request, response, routeData) => response.WriteAsync($"{name} - API Get {routeData.Values["id"]}"));
});
}
}
}
|