Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a URL outside of a controller in ASP.NET MVC?

How do I generate a URL pointing to a controller action from a helper method outside of the controller?

like image 233
Shawn Mclean Avatar asked Feb 05 '11 15:02

Shawn Mclean


People also ask

How redirect external URL from view in MVC?

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.

How do you give a controller a URL?

If you just want to get the path to a certain action, use UrlHelper : UrlHelper u = new UrlHelper(this. ControllerContext. RequestContext); string url = u.


2 Answers

You could use the following if you have access to the HttpContext:

var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext); 
like image 101
L01NL Avatar answered Sep 30 '22 15:09

L01NL


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

like image 33
mohammadmahdi Talachi Avatar answered Sep 30 '22 13:09

mohammadmahdi Talachi