How do I generate a URL pointing to a controller action from a helper method outside of the controller?
You can redirect to an external URL by using Redirect Method() or via Json Result. Asp.net MVC redirect to URL: You can do URL redirect in mvc via Controller's Redirect() method.
If you just want to get the path to a certain action, use UrlHelper : UrlHelper u = new UrlHelper(this. ControllerContext. RequestContext); string url = u.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With