2

中爲操作URL添加自定義查詢參數在ASP.NET Core MVC中,我希望這樣做的目的是使用Url.Action和基於動作的標記助手創建的URL在URL中包含自定義查詢參數。無論控制器或操作如何,我都想在全球範圍內應用此功能。在ASP.NET Core MVC

我試過overriding the default route handler,它曾經在一起工作過,但打破了ASP.NET Core更新。我究竟做錯了什麼?有沒有更好的辦法?

回答

2

嘗試將其添加到集合中,而不是覆蓋DefaultHandler。以下爲我工作的1.1.2版本:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
    // ... other configuration 
    app.UseMvc(routes => 
    { 
     routes.Routes.Add(new HostPropagationRouter(routes.DefaultHandler)); 
     routes.MapRoute(
      name: "default", 
      template: "{controller=Home}/{action=Index}/{id?}"); 
    }); 
    // ... other configuration 
} 

這裏的路由器,只是爲了完整性。

public class HostPropagationRouter : IRouter 
{ 
    readonly IRouter router; 

    public HostPropagationRouter(IRouter router) 
    { 
     this.router = router; 
    } 

    public VirtualPathData GetVirtualPath(VirtualPathContext context) 
    { 
     if (context.HttpContext.Request.Query.TryGetValue("host", out var host)) 
      context.Values["host"] = host; 
     return router.GetVirtualPath(context); 
    } 

    public Task RouteAsync(RouteContext context) => router.RouteAsync(context); 
} 
+0

工作,但我希望我能更好地理解爲什麼。你能解釋或指出IRUteBuilder.Routes和IRouteBuilder.DefaultHandler是如何相互交互以及通過MapRoute創建的路徑的文檔嗎? –

+0

@EdwardBrey我不知道足以回答你的問題。但是,我確實知道行爲的變化[與此錯誤修復相關](https://github.com/aspnet/Routing/issues/370)。傳遞的值沒有被正確地傳遞下去。 –