【问题标题】:Add custom query parameter to action URL in ASP.NET Core MVC在 ASP.NET Core MVC 中将自定义查询参数添加到操作 URL
【发布时间】:2017-11-15 10:35:12
【问题描述】:

在 ASP.NET Core MVC 中,我希望使用 Url.Action 和基于操作的标签助手创建的 URL 在 URL 中包含自定义查询参数。无论控制器或操作如何,我都想在全球范围内应用它。

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

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc url-routing query-parameters


    【解决方案1】:

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

    【讨论】:

    • 那行得通,但我希望我能更好地理解原因。您能否解释或指出有关 IRouteBuilder.RoutesIRouteBuilder.DefaultHandler 如何相互交互以及如何与通过 MapRoute 创建的路由交互的文档?
    • @EdwardBrey 我没有足够的知识来明确回答您的问题。但是,我知道行为的变化是related to this bug fix。传递的值未正确传递。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 2016-06-22
    • 1970-01-01
    • 2012-09-05
    相关资源
    最近更新 更多