Reputation: 6712
Id' like to retrieve a url to my website from global asax. This url has to be complete (protocol, domain, etc.). Is there an easy way to do that?
I tried VirtualPathUtility.ToAbsolute
but it only gives a relative path.
Upvotes: 4
Views: 25205
Reputation: 542
You can achieve this by using Application_BeginRequest method in your Global.asax and HttpApplication.Context.Request.Url. Keep in mind that the method is going to fire for every request.
public class Global : System.Web.HttpApplication
{
private void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_BeginRequest(Object source, EventArgs e)
{
var app = (HttpApplication)source;
var uriObject = app.Context.Request.Url;
//app.Context.Request.Url.OriginalString
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs on application error
}
private void RegisterRoutes(RouteCollection routes)
{
// Code that runs on register routes
}
}
Upvotes: 5
Reputation: 2497
It is not possible to get the URL during the Application_Start method of the Global.asax. As @Edwin noted, you can do it inside the Application_BeginRequest, but this fires for every request made, not just the first one. If this is an issue you'll need to setup an initializer that though called for each request, only fires once.
Here's an article on the issue: http://mvolo.com/iis7-integrated-mode-request-is-not-available-in-this-context-exception-in-applicationstart/
And the relevant bits:
void Application_BeginRequest(Object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
// Attempt to peform first request initialization
FirstRequestInitialization.Initialize(context);
}
class FirstRequestInitialization
{
private static bool s_InitializedAlready = false;
private static Object s_lock = new Object();
// Initialize only on the first request
public static void Initialize(HttpContext context)
{
if (s_InitializedAlready)
return;
lock (s_lock)
{
if (s_InitializedAlready)
return;
/* << Perform first-request initialization here >> */
s_InitializedAlready = true;
}
}
}
Upvotes: 2
Reputation: 6712
Thanks to Royi I now remembered how to do that (long time I hadn't done it) :
var url = HttpContext.Current.Request.Url;
bar myUrl = url.AbsoluteUri.Replace(url.PathAndQuery, VirtualPathUtility.ToAbsolute("~/WS/someFolder/someService.svc"));
Upvotes: 1
Reputation: 148714
Try this :
HttpContext.Current.Request.Url.OriginalString
This way you can access the url from global asax.
P.s. you could have done it yourself by debugging :
OriginalString
was used cuz you wanted the full origin info.
you can also use the one without the port which is AbsoluteURI
Upvotes: 13