想在 ASP.NET Core 6 中基于 X-Forwarded-Host
请求头(request header)路由到对应的 Controller Action,请问如何实现?
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
111111