asp.net – 在集成模式下替换HttpContext.Current.Request.ServerVariables [“SERVER_NAME”]

在集成模式下使用HttpContext.Current.Request.ServerVariables [“SERVER_NAME”]会在IIS7中出现错误,如下所示: http://mvolo.com/blogs/serverside/archive/2007/11/10/Integrated-mode-Request-is-not-available-in-this-context-in-Application_5F00_Start.aspx

我可以在global.asax代码中使用HttpContext.Current.Request.ServerVariables [“SERVER_NAME”]吗?

这与使用类似

String strPath = 
HttpContext.Current.Server.MapPath(HttpRuntime.AppDomainAppVirtualPath);

代替

//String strPath = 
HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ServerVariables["PATH_INFO"]);

解决方法

由于在应用程序启动期间管道中没有请求上下文,我无法想象有什么方法可以猜测下一个实际请求可能出现在哪个服务器/端口上.

这是我在经典模式下使用的内容.开销可以忽略不计.

/// <summary>
/// Class is called only on the first request
/// </summary>
private class AppStart
{
    static bool _init = false;
    private static Object _lock = new Object();

    /// <summary>
    /// Does nothing after first request
    /// </summary>
    /// <param name="context"></param>
    public static void Start(HttpContext context)
    {
        if (_init)
        {
            return;
        }
        //create class level lock in case multiple sessions start simultaneously
        lock (_lock)
        {
            if (!_init)
            {
                string server = context.Request.ServerVariables["SERVER_NAME"];
                string port = context.Request.ServerVariables["SERVER_PORT"];
                httpruntime.cache.Insert("basePath","http://" + server + ":" + port + "/");
            }
        }
    }
}

protected void Session_Start(object sender,EventArgs e)
{
    //initializes Cache on first request
    AppStart.Start(HttpContext.Current);
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....