UseRouterStartup.cs 2.3 KB

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