patterncsharpCritical
Getting full URL of action in ASP.NET MVC
Viewed 0 times
actionnetaspurlfullgettingmvc
Problem
Is there a built-in way of getting the full URL of an action?
I am looking for something like
The reason I am looking for this is to avoid hardcoding URLs in automated emails that are generated so that the URLs can always be generated relative to the current location of the site.
I am looking for something like
GetFullUrl("Action", "Controller") that would return something like http://www.fred.com/Controller/Action.The reason I am looking for this is to avoid hardcoding URLs in automated emails that are generated so that the URLs can always be generated relative to the current location of the site.
Solution
There is an overload of Url.Action that takes your desired protocol (e.g. http, https) as an argument - if you specify this, you get a fully qualified URL.
Here's an example that uses the protocol of the current request in an action method:
HtmlHelper (@Html) also has an overload of the ActionLink method that you can use in razor to create an anchor element, but it also requires the hostName and fragment parameters. So I'd just opt to use @Url.Action again:
Here's an example that uses the protocol of the current request in an action method:
var fullUrl = this.Url.Action("Edit", "Posts", new { id = 5 }, this.Request.Url.Scheme);HtmlHelper (@Html) also has an overload of the ActionLink method that you can use in razor to create an anchor element, but it also requires the hostName and fragment parameters. So I'd just opt to use @Url.Action again:
Copy
this link
and post it anywhere on the internet!
Code Snippets
var fullUrl = this.Url.Action("Edit", "Posts", new { id = 5 }, this.Request.Url.Scheme);<span>
Copy
<a href='@Url.Action("About", "Home", null, Request.Url.Scheme)'>this link</a>
and post it anywhere on the internet!
</span>Context
Stack Overflow Q#2005367, score: 628
Revisions (0)
No revisions yet.