如何在ASP.NET中获取主机域名,而不使用HttpContext.Current.Request? [英] How do I get the host domain name in ASP .NET without using HttpContext.Current.Request?

查看:138
本文介绍了如何在ASP.NET中获取主机域名,而不使用HttpContext.Current.Request?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在IIS7上运行的ASP .Net应用程序。我正在使用网站运行的当前网址,以在我的应用程序中的类上设置一些静态属性。为此,我使用这个域名(insde该类的静态构造函数):

  var host = HttpContext。 Current.Request.Url.Host; 

它在我的开发机器(Windows XP / Cassini)上工作正常。但是,当我部署到IIS7时,我收到一个例外:请求在此上下文中不可用。



我猜这是因为我在一个对象的静态构造函数中使用这个代码,这是在任何请求进入之前在IIS中执行的;而在发生请求之前,Cassini不会触发静态构造函数。现在,我根本不喜欢从请求中提取域名的想法,但这是我发现的唯一的地方。=)



所以有没有人知道我可以得到主机域名的另一个地方?我假设ASP .Net必须在某种程度上独立于HttpRequests来了解它,我只是不知道如何访问它。

解决方案

域名在请求中的原因是...这是要求的。例如,这些是 http://www.stackexchangesites.com/ 的几个stackexchange网站:





如果你ping它们,你会看到他们都指向同一个IP / Web服务器,并由相同的应用程序(或在这种情况下的多个应用程序) ,但是如果它是一个大的例子,那么这个例子是...),但应用程序不知道哪一个,直到主机标头来自服务器请求该站点的请求。每个请求可能是一个不同的域,所以应用程序不知道。



如果不改变,你可以将其存储为一个appSetting在 web.config 中。


I've got an ASP .Net application running on IIS7. I'm using the current url that the site is running under to set some static properties on a class in my application. To do this, I'm getting the domain name using this (insde the class's static constructor):

var host = HttpContext.Current.Request.Url.Host;

And it works fine on my dev machine (windows XP / Cassini). However, when I deploy to IIS7, I get an exception: "Request is not available in this context".

I'm guessing this is because I'm using this code in the static constructor of an object, which is getting executed in IIS before any requests come in; and Cassini doesn't trigger the static constructor until a request happens. Now, I didn't originally like the idea of pulling the domain name from the Request for this very reason, but it was the only place I found it =)

So, does anyone know of another place that I can get the host domain name? I'm assuming that ASP .Net has got to be aware of it at some level independent of HttpRequests, I just don't know how to access it.

解决方案

The reason that the domain is in the request is...that's what's being asked for. For example these are a few stackexchange sites from http://www.stackexchangesites.com/:

If you ping them, you'll see they all point to the same IP/Web Server and be served by the same app (or multiple apps in this case, but the example holds if it was one big one)...but the application doesn't know which one until a host header comes in with the request asking the server for that site. Each request may be to a different domain...so the application doesn't know it.

If however it doesn't change, you could store it as an appSetting in the web.config.

这篇关于如何在ASP.NET中获取主机域名,而不使用HttpContext.Current.Request?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆