ASP.NET MVC create absolute url from c# code
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 c开发者_高级运维an be done in the views?
It wont be generated inside the controller but inside a ViewModel.
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 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
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
精彩评论