Tag helpers not working with DynamicRouteValueTransformer

Viewed 394

ASP.NET Core's tag helpers appear not to be working in combination with DynamicRouteValueTransformer.

Here's an MCVE: let's say we have a simple controller with two actions...

public class GenericController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Add()
    {
        return View();
    }
}

... and the Index view links to the Add action with the asp-action tag helper:

<!DOCTYPE html>
<html>
<body>
   <a asp-action="Add">Add new!</a>
</body>
</html>

When we now open /Generic in a browser and inspect the page, we'll notice that ASP.NET generated the expected href value for the controller action:

<a href="/Generic/Add">Add new!</a>

So far, so good. Now let's create a DynamicRouteValueTransformer which routes all requests to that same controller...

    public class Transformer : DynamicRouteValueTransformer
    {
        public override ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
        {
            if (values.ContainsKey("controller"))
            {
                values["originalController"] = values["controller"];
                values["controller"] = "Generic";
            }
            return new ValueTask<RouteValueDictionary>(values);
        }
    }

... and let's set it up for endpoint routing in Startup.cs...

            services.AddSingleton<Transformer>();
...
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDynamicControllerRoute<Transformer>("{controller=Home}/{action=Index}/{id?}");
            });

After opening /Generic (or any other route, e.g. /Foobar) in a browser and inspecting the page, we'll now notice that asp-action tag helper is no longer working:

<a href="">Add new!</a>

Since the href value is empty, the link is no longer working. It looks the dynamic routing broke the tag helper.

Any suggested fix or workaround?

0 Answers
Related