Determine the URL hostname without using HttpContext.Current?

99封情书 提交于 2019-12-03 23:30:27

If you know the host at the moment you're setting up the event handler then you should be able to do something like (code not actually tested):

string host = HttpContext.Current.Request.Url.Host;
var dep = new SqlDependency(cmd);
dep.OnChange += ((sender, args) =>
{
    DoStuff(host);
});

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.

How about

Environment.MachineName
Thorsten Hans

You should use the IIS api to query the information from the website you're looking for. Because depending on the IIS configuration your URL or Hostname could be differing. (Think about hostheaders, ports, protocols and stuff like this.

A introduction for IIS API could be found at http://learn.iis.net/page.aspx/165/how-to-use-microsoftwebadministration/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!