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

标签 asp.net-core asp.net-core-mvc url-routing query-string

在 ASP.NET Core MVC 中,我希望使用 Url.Action 创建的 URL 和基于操作的标记帮助程序在 URL 中包含自定义查询参数。我想在全局范围内应用此功能,无论 Controller 或操作如何。

我试过overriding the default route handler ,它曾经有效,但随着 ASP.NET Core 更新而崩溃。我究竟做错了什么?有更好的办法吗?

最佳答案

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

关于asp.net-core - 将自定义查询参数添加到 ASP.NET Core MVC 中的操作 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44525040/

相关文章:

c# - 下载存储的 PDF 时损坏

asp.net-core - 用户 secret 文件在 asp.net core 6 中被忽略

c# - Web API ASP.NET Core 发布请求 415 不支持的媒体类型

asp.net-core - 如何在asp.net core 1.0中获取当前的url

c# - 使用 MVC Core 时将参数传递给 main 方法

c# - 为什么我的隐藏输入没有在模型类中传递?

c# - Blazor 服务器端的 Asp.Net Core Identity

php - URL 路由与多个脚本

javascript - FOSJsRoutingBundle 不识别路由

php - 如何获取cakephp中的基本Url?