在一个 ASP.NET Core 项目中,添加了下面的属性路由配置:
[Route("{brand}")]
public class BrandController : Controller
{
[Route("home/{pageIndex:int?}")]
public async Task<IActionResult> Home(string brand, int? pageIndex = 1)
{
// ...
return View($"~/Views/Brands/{model.Brand}/Home.cshtml", model);
}
}
想实现根据 brand
的值进行路由,比如请求路径是 /huawei
,就走上面的路由,否则走默认路由。
后来实际采用的解决方法如下。
实现 BrandRouteValueTransformer
public class BrandRouteValueTransformer : DynamicRouteValueTransformer
{
public override ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
{
if (values.TryGetValue("brand", out var brand))
{
if (BrandCollection.All.Any(b => b.Equals(brand.ToString(), StringComparison.OrdinalIgnoreCase)))
{
values["controller"] = "Brand";
if (!values.TryGetValue("action", out var action))
{
values["action"] = "Home";
}
}
}
return new ValueTask<RouteValueDictionary>(values);
}
}
Startup.ConfigureServices 中注册
services.AddSingleton<BrandRouteValueTransformer>();
Startup.Configure 中添加路由
endpoints.MapDynamicControllerRoute<BrandRouteValueTransformer>("{brand}/{**slug}");
Program.Main 中打补丁
AppContext.SetSwitch("Microsoft.AspNetCore.Routing.UseCorrectCatchAllBehavior", true);