将自定义查询参数添加到 ASP.NET Core MVC 中的操作 URL

Add custom query parameter to action URL in ASP.NET Core MVC

在 ASP.NET Core MVC 中,我想使 URL 使用 Url.Action 和基于操作的标签助手创建的 URL 在 URL。我想在全球范围内应用它,而不考虑控制器或操作。

我尝试了 overriding the default route handler,它曾一度有效,但因 ASP.NET 核心更新而中断。我究竟做错了什么?有没有更好的方法?

尝试将其添加到集合中而不是覆盖 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);
}