2

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?

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

That worked, but I wish I better understood why. Can you explain or point to documentation on how IRouteBuilder.Routes and IRouteBuilder.DefaultHandler interact with each other and with routes created through MapRoute?
@EdwardBrey I don't know enough to answer your question definitively. However, I do know that the change in behavior is related to this bug fix. The values being passed were not properly being passed down the line.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.