Web Design, Programming, Tutorials
ASP.NET MVC Full URL From A Controller
In working with ASP.NET MVC, I came across the need to send an email with the URL of a document that is to be approved. There are helper functions accessible from the View to build an ActionLink or get the URL of an action, but I had problems finding how to build this URL from within a controller. Here is the simple code that I finally pieced together to do what I wanted:
Dim link As String = HttpContext.Request.Url.Scheme + _
"://" + HttpContext.Request.Url.Authority + _
Url.Action("ActionName", "ControllerName", New With {.id = idOfDocument})
HttpContext.Request.Url.Scheme returns “http” or “https”, which ever one you’re using.
HttpContext.Request.Url.Authority returns the Base Url of your application.
And, the Url.Action method creates the Url to the Controller, Action, and ID of the document that is being sent out for approval.
about 2 years ago
Hmm… I read blogs on a similar topic, but i never visited your blog. I added it to favorites and i’ll be your constant reader.
about 2 years ago
Hello from Russia!
Can I quote a post in your blog with the link to you?
about 2 years ago
Yes.
about 1 year ago
Nice! Might I suggest making this an extension method for a controller and using the controller’s context.RequestContext to build the url? This way this is both encapsulated nicely, and mockable!
about 1 year ago
@Brenton Unger
Yes. I’ve recently been using a wrapper class to contain functions and properties that access the HttpContext.
I use an interface to make the wrapper class passable into my service and data access layers. The service/data access classes only need to know about the interface (not that it uses HttpContext), so my service/data access layers are not tightly coupled to MVC.
I guess it depends on where you need to use the full URL, but either a wrapper class or extension method sounds like a good place to me! Great suggestion!
about 1 year ago
After research a couple of of the weblog posts in your web site now, and I really like your method of blogging. I bookmarked it to my bookmark web site checklist and will be checking again soon. Pls try my website as properly and let me know what you think.