如何在 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
有人知道如何实现吗?
推荐答案
当您的 Web 应用程序启动时,没有处理 HTTP 请求.
When your web application starts, there is no HTTP request being handled.
您可能想要处理定义 Application_BeginRequest(Object Sender, EventArgs e) 方法,其中请求上下文可用.
You may want to handle define the Application_BeginRequest(Object Sender, EventArgs e) method in which the the Request context is available.
这是一个受 Michael Shimmins 链接到的 Mike Volodarsky 博客启发的代码示例:
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屋!
查看全文