Reputation: 2534
Is there a way to force my ASP.NET Core 2.0 app to use a custom UrlHelper I've written everywhere?
I have a class with custom logic
public class CustomUrlHelper : UrlHelper { ... }
I want it to be used everywhere, so that urls are generated according to our custom business rules.
Upvotes: 2
Views: 821
Reputation: 141632
Create a CustomUrlHelper
and a CustomUrlHelperFactory
.
public class CustomUrlHelper : UrlHelper
{
public CustomUrlHelper(ActionContext actionContext)
: base(actionContext) { }
public override string Action(UrlActionContext actionContext)
{
var controller = actionContext.Controller;
var action = actionContext.Action;
return $"You wrote {controller} > {action}.";
}
}
public class CustomUrlHelperFactory : IUrlHelperFactory
{
public IUrlHelper GetUrlHelper(ActionContext context)
{
return new CustomUrlHelper(context);
}
}
Then open your Statup.cs
file and register the CustomUrlHelperFactory
in the ConfigureServices
method.
services.AddMvc();
services.AddSingleton<IUrlHelperFactory, CustomUrlHelperFactory>();
After doing that, your app will use the CustomUrlHelper
everywhere. That includes calls to @Url.Action("Index", "Home")
from a razor page.
Upvotes: 2