Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC create absolute url from c# code

Tags:

asp.net-mvc

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.

like image 492
Shawn Mclean Avatar asked Nov 27 '10 20:11

Shawn Mclean


People also ask

How to get base URL in MVC c#?

How to Get the Base URL in an MVC Controller. Here's a simple one-liner to get the job done. var baseUrl = string. Format(“{0}://{1}{2}”, Request.

How do I get the absolute URL in .NET core?

By specifying the protocol and host, the result is now "https://your-website/Home/Privacy" . However, if you omit the host parameter but keep the protocol parameter, the result will still be an absolute URL, because the host parameter will default to the host used for the current HTTP request.

How do I change the default URL in MVC?

How do I change the default page in ASP NET MVC? You can set up a default route: routes. MapRoute( "Default", // Route name "", // URL with parameters new { controller = "Home", action = "Index"} // Parameter defaults ); Just change the Controller/Action names to your desired default.

What is URL RouteUrl?

RouteUrl(String, RouteValueDictionary, String, String) Generates a fully qualified URL for the specified route values by using the specified route name, protocol to use, and host name.


2 Answers

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.

like image 98
Shawn Mclean Avatar answered Oct 05 '22 16:10

Shawn Mclean


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

like image 45
Erik Philips Avatar answered Oct 05 '22 17:10

Erik Philips