Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the URL hostname without using HttpContext.Current?

Using the current request I can get the URL hostname with:

HttpContext.Current.Request.Url.Host

But - I need to determine the URL hostname without using the current request (HttpContext.Current). The reason for this is that my code is called from a SqlDependency in the onChange callback for when a SQL Dependency is found. Althougth the code resides in my web app, there is no request, and HttpContext.Current is null.

I was hoping I could grab it from HttpRuntime, but there doesn't seem to be anything of use there. is there a way I can get this information?

like image 438
Matt Roberts Avatar asked Jan 12 '12 11:01

Matt Roberts


People also ask

Which method will get current application hosting domain name?

GetCurrentDomain method is determined by the domain credentials under which the application is running.

What HttpContext current?

What is HttpContext? It holds the current information about the Http request. It contains the information like authorization, authentication, request, response, session, items, users, formOptions, etc. Every HTTP request creates a new object of HttpContext with current information.


2 Answers

If you are running this from a web application, and it is all managed code then HttpContext must exist. Does your child library (assuming your managed code is in a library) have a reference to System.Web? If not, consider adding this reference. From that point you should be able to access the HttpContext directly by using the fully qualified namespace:

System.Web.HttpContext.Current.Request.Url.Host

In any case, unless your code is unmanaged or your context truly does not originate with a web application, HttpContext should be available at every point while the thread is alive.

Edit:
Based on reading your comment below, it sounds like the SqlDependency is being fired independently. While it's on the same thread, it's not being fired directly by the request. Since all you're looking for is the host url, it's not inconceivable that you can create an application variable or a static variable to hold this information in the event that it is needed for a dependency.

Also something I have seen is that while HttpContext.Current may not be available, HttpContext.Request might be. These should be the same object, but they may not necessarily be. It's possible that the Host may be found there.

like image 50
Joel Etherton Avatar answered Sep 21 '22 14:09

Joel Etherton


How about

Environment.MachineName
like image 41
Wiktor Zychla Avatar answered Sep 25 '22 14:09

Wiktor Zychla