How do I generate a URL outside of a controller in ASP.NET MVC?
You could use the following if you have access to the HttpContext
:
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
You can use LinkGenerator . It's new feature in Microsoft.AspNetCore.Routing namespace and has been added in Aug 2020 .
At first you have to inject that in your class :
public class Sampleervice
{
private readonly LinkGenerator _linkGenerator;
public Sampleervice (LinkGenerator linkGenerator)
{
_linkGenerator = linkGenerator;
}
public string GenerateLink()
{
return _linkGenerator.GetPathByAction("Privacy", "Home");
}
}
For more information check this