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.

You may also like...

8 Responses

  1. Clemento says:

    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.

  2. Polprav says:

    Hello from Russia!
    Can I quote a post in your blog with the link to you?

  3. 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!

  4. @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!

  5. Valium says:

    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.

  6. Card Transaction says:

    What’s up, just wanted to tell you, I liked this article. It was practical. Keep on posting!

  1. October 20, 2009

    […] to VoteASP.NET MVC Full URL From A Controller (10/16/2009)Friday, October 16, 2009 from Chris JacksonIn working with ASP.NET MVC, I came across the need to […]

Leave a Reply

Your email address will not be published. Required fields are marked *