Reputation: 41658
In ASP.NET Core MVC, I'd like to make it so that URLs created with Url.Action
and action-based tag helpers include a custom query parameter in the URL. I want to apply this globally, regardless of the controller or action.
I tried overriding the default route handler, which worked at one time, but broke with an ASP.NET Core update. What am I doing wrong? Is there a better way?
Upvotes: 2
Views: 2176
Reputation: 10889
Try adding it to the collection instead of overriding the DefaultHandler
. The following worked for me on version 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
}
Here's the router, just for completeness.
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);
}
Upvotes: 2