[英]ASP.NET Core: Is there a way to make UrlHelper functions (Url.Action, etc.) work with dynamic routing?
這是 .NET Core 3.1(嘗試使用 5.0 和 6.0,結果相同)。
我正在嘗試為我們的應用程序切換到動態路由,這有效,但它會導致通過應用程序返回 null 的所有 Url.Action() 調用。
在具有相同結果的示例應用程序中進行了嘗試。 所以在 Startup.cs 中,我調用了 endpoints.MapDynamicControllerRoute(...),而不是使用 endpoints.MapControllerRoute(...)。 例如:
app.UseEndpoints(endpoints =>
{
// endpoints.MapControllerRoute(
// name: "default",
// pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapDynamicControllerRoute<TestSearchTransformer>("{controller=Home}/{action=Index}");
});
其中 TestSearchTransformer 只是簡單的傳遞:
class TestSearchTransformer : DynamicRouteValueTransformer
{
public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
{
return values;
}
}
當使用 MapControllerRoute 調用 Url.Action("Index", "Home") 按預期返回“/Home/Index”,但使用 MapDynamicControllerRoute 時它返回 null。
我錯過了什么?
謝謝你。
我找到了一個解決方案,我對此並不特別興奮。 顯然,您可以創建自己的自定義 UrlHelper class(基於此Overwriting UrlHelper with a CustomUrlHelper - ASP.NET CORE 2.0 )並覆蓋其中的 Action 方法:
public override string Action(UrlActionContext actionContext)
這可行,但需要您編寫自己的鏈接生成邏輯。 所以這並不理想。 我仍然想知道是否有更好的方法。
也許您錯過了注冊 TestSearchTransformer 的機會。 在您的 ConfigureServices 中添加:
services.AddSingleton<TestSearchTransformer>();
下面是一個工作演示,你可以參考它。
啟動
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton<TestSearchTransformer>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
//endpoints.MapControllerRoute(
// name: "default",
// pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapDynamicControllerRoute<TestSearchTransformer>("{controller=home}/{action=index}");
});
}
}
測試搜索轉換器
public class TestSearchTransformer : DynamicRouteValueTransformer
{
public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
{
return values;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.