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.
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.
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 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.
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.
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.
Check out a similar question Using html actionlink and URL action from inside controller. Seems to be similar and reusable for your requirements.
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