如何获得完整的主机名+端口号Global.aspx中的Application_Start? [英] How to get full host name + port number in Application_Start of Global.aspx?
本文介绍了如何获得完整的主机名+端口号Global.aspx中的Application_Start?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试过
Uri uri = HttpContext.Current.Request.Url;
String host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
和它的工作以及我的本地机器上,但是当被发布到IIS7,有异常说法
and it worked well on my local machine, but when being published to IIS7, there is an exception saying
System.Web.HttpException: Request is not available in this context
任何人都知道如何实现这一目标?
Anyone know how to achieve this?
推荐答案
在你的web应用程序启动时,没有被处理没有HTTP请求。
When your web application starts, there is no HTTP request being handled.
您可能要处理定义的Application_BeginRequest(对象发件人,EventArgs五)方法,其中请求上下文是可用的。
You may want to handle define the Application_BeginRequest(Object Sender, EventArgs e) method in which the the Request context is available.
编辑:这是由迈克沃洛达尔斯基的博客的启发code样品迈克尔Shimmins链接到:
Here is a code sample inspired by the Mike Volodarsky's blog that Michael Shimmins linked to:
void Application_BeginRequest(Object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
var host = FirstRequestInitialisation.Initialise(app.Context);
}
static class FirstRequestInitialisation
{
private static string host = null;
private static Object s_lock = new Object();
// Initialise only on the first request
public static string Initialise(HttpContext context)
{
if (string.IsNullOrEmpty(host))
{
lock (s_lock)
{
if (string.IsNullOrEmpty(host))
{
var uri = context.Request.Url;
host = uri.GetLeftPart(UriPartial.Authority);
}
}
}
return host;
}
}
这篇关于如何获得完整的主机名+端口号Global.aspx中的Application_Start?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文