27

How do i generate an absolute url from the c# code?

I want to generate a url like this: localhost/{controller}/{action}/{id}. Is there a way to do it in c# like how it can be done in the views?

It wont be generated inside the controller but inside a ViewModel.

Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

4 Answers4

71
string absUrl = Url.Action("Index", "Products", null, Request.Url.Scheme);

Just add Request.Url.Scheme. What this does is add a protocol to the url which forces it to generate an absolute URL.

Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406
  • 1
    Thanks, this was so well hidden I almost used `Url.RouteUrl`. – Peter Apr 24 '12 at 14:10
  • 3
    And if you want to generate a fully-qualified url using the Url.Action("Index") overload (where you do not specify the controller), just pass in **null** as the controller parameter. This leads to: `Url.Action("Index", null, null, Request.Url.Scheme)` . – Erik Schierboom Dec 15 '12 at 11:24
1

Check out a similar question Using html actionlink and URL action from inside controller. Seems to be similar and reusable for your requirements.

Community
  • 1
  • 1
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
0

As of latest update to MVC you can use below overload for Url.Action

string url=Url.Action("ActionName", "Controller", 
                       new RouteValueDictionary(new { id= someid }), 
                                                      //url param
                       HttpContext.Request.Url.Scheme, 
                       HttpContext.Request.Url.Host);

which generates

http://localhost:port/Controller/ActionName?id=someid
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
0

If you don't want to "build" the url and just want the full path of the current page, this will do the trick

Context.Server.UrlEncode(Context.Request.Url.AbsoluteUri)

I know it's not as elegant as an Extension Method but thought of sharing it for educational purposes

Korayem
  • 12,108
  • 5
  • 69
  • 56