ASP.NET Core 6 中如何实现基于请求头的路由

DynamicRouteValueTransformer 专治路由疑难杂症,用它解决了

1)继承 DynamicRouteValueTransformer 实现 DemoRouteValueTransformer

public class DemoRouteValueTransformer : DynamicRouteValueTransformer { public override ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values) { if (httpContext.Request.Headers.TryGetValue("X-Forwarded-Host", out var forwardedHost) && forwardedHost.ToString().Equals("q.cnblogs.com", StringComparison.OrdinalIgnoreCase)) { values = values ?? new RouteValueDictionary(); values["controller"] = "Home"; values["action"] = "Demo"; } return ValueTask.FromResult(values); } } 

2)注册 DemoRouteValueTransformer 到 DI 容器

services.AddScoped<DemoRouteValueTransformer>(); 

3)添加动态路由规则

app.UseEndpoints(endpoints => { endpoints.MapDynamicControllerRoute<DemoRouteValueTransformer>("/"); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); 

注:MapDynamicControllerRoute 要放在 MapControllerRoute 之前,不然会走 MapControllerRoute 默认路由 /Home/Index

原文链接:https://q.cnblogs.com/q/138077/

更多内容