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

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

问题描述

我有一个在 IIS7 上运行的 ASP .Net 应用程序.我正在使用站点运行的当前 url 在我的应用程序中的类上设置一些静态属性.为此,我使用这个(插入类的静态构造函数)获取域名:

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;

它在我的开发机器(Windows XP/Cassini)上运行良好.但是,当我部署到 IIS7 时,出现异常:请求在此上下文中不可用".

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".

我猜这是因为我在对象的静态构造函数中使用了此代码,该对象在任何请求进来之前在 IIS 中执行;并且 Cassini 在请求发生之前不会触发静态构造函数.现在,由于这个原因,我最初并不喜欢从请求中提取域名的想法,但这是我找到它的唯一地方 =)

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 =)

那么,有谁知道我可以获得主机域名的其他地方吗?我假设 ASP .Net 必须在某种程度上独立于 HttpRequests,我只是不知道如何访问它.

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.

推荐答案

域在请求中的原因是……这就是请求的内容.例如,这些是来自 http://www.stackexchangesites.com/ 的一些 stackexchange 站点:

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/:

如果您对它们执行 ping 操作,您会看到它们都指向同一个 IP/Web 服务器并由同一个应用程序提供服务(或在本例中为多个应用程序,但如果它是一个大应用程序,则该示例成立)..但应用程序直到 主机头 伴随着向服务器询问该站点的请求.每个请求可能发送到不同的域...所以应用程序不知道.

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.

如果它没有改变,你可以将它作为 appSetting 存储在 web.config 中.

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

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

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