Reputation: 57469
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.
Upvotes: 27
Views: 18587
Reputation: 29683
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
Upvotes: 0
Reputation: 12497
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
Upvotes: 0
Reputation: 57469
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.
Upvotes: 71
Reputation: 54618
Check out a similar question Using html actionlink and URL action from inside controller. Seems to be similar and reusable for your requirements.
Upvotes: 1