在 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/