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)。传递的值没有被正确地传递下去。 –