请求在此上下文中不可用

时间:2022-02-26 09:40:45

I'm running IIS 7 Integrated mode and I'm getting

我正在运行iis7集成模式

Request is not available in this context

请求在此上下文中不可用

when I try to access it in a Log4Net related function that is called from Application_Start. This is the line of code I've

当我尝试在与Log4Net相关的函数中访问它时,它会从Application_Start调用。这是我的代码行

if (HttpContext.Current != null && HttpContext.Current.Request != null)

and an exception is being thrown for second comparison.

一个异常被抛出以进行第二次比较。

What else can I check other than checking HttpContext.Current.Request for null??

除了检查HttpContext.Current之外,我还能检查什么。要求零? ?


A similar question is posted @ Request is not available in this context exception when runnig mvc on iis7.5

当在iis7.5上运行mvc时,在这个上下文异常中没有发布类似的问题@ Request

but no relevant answer there either.

但也没有相关的答案。

9 个解决方案

#1


69  

Please see IIS7 Integrated mode: Request is not available in this context exception in Application_Start:

请参见IIS7集成模式:请求在Application_Start的此上下文异常中不可用:

The “Request is not available in this context” exception is one of the more common errors you may receive on when moving ASP.NET applications to Integrated mode on IIS 7.0. This exception happens in your implementation of the Application_Start method in the global.asax file if you attempt to access the HttpContext of the request that started the application.

“请求在此上下文中不可用”异常是您在移动ASP时可能遇到的最常见错误之一。NET应用程序集成模式在IIS 7.0。在全局的Application_Start方法的实现中发生了这个异常。如果您试图访问启动应用程序的请求的HttpContext,请使用asax文件。

#2


37  

When you have custom logging logic, it is rather annoying to be forced either not to log application_start or to have to let an exception occurs in the logger (even if handled).

当您有自定义日志记录逻辑时,强制不记录application_start或必须让日志记录器中发生异常(即使已处理)是相当烦人的。

It appears that rather than testing for Request availability, you can test for Handler availability: when there is no Request, it would be strange to still have a request handler. And testing for Handler does not raise that dreaded Request is not available in this context exception.

与测试请求可用性不同,您可以测试处理程序的可用性:当没有请求时,仍然有一个请求处理程序是奇怪的。并且,对Handler的测试不会引发这个上下文异常中不可用的可怕请求。

So you may change your code to:

因此,您可以将代码更改为:

var currContext = HttpContext.Current;
if (currContext != null && currContext.Handler != null)

Beware, in the context of an http module, Handler may not be defined though Request and Response are defined (I have seen that in BeginRequest event). So if you need request/response logging in a custom http module, my answer may not be suitable.

注意,在http模块的上下文中,可能没有通过定义请求和响应来定义处理程序(我在BeginRequest事件中见过)。因此,如果需要在自定义http模块中进行请求/响应日志记录,我的回答可能不太合适。

#3


13  

This is very classic case: If you end up having to check for any data provided by the http instance then consider moving that code under the BeginRequest event.

这是非常典型的情况:如果您最终不得不检查http实例提供的任何数据,那么请考虑在BeginRequest事件下移动该代码。

void Application_BeginRequest(Object source, EventArgs e)

This is the right place to check for http headers, query string and etc... Application_Start is for the settings that apply for the application entire run time, such as routing, filters, logging and so on.

这是检查http头、查询字符串等的正确位置。Application_Start用于应用程序整个运行时的设置,例如路由、过滤器、日志记录等等。

Please, don't apply any workarounds such as static .ctor or switching to the Classic mode unless there's no way to move the code from the Start to BeginRequest. that should be doable for the vast majority of your cases.

请不要应用任何变通方法,例如静态.ctor或切换到经典模式,除非没有办法将代码从开始移动到开始请求。这对你的绝大多数案例都是可行的。

#4


6  

Since there's no Request context in the pipeline during app start anymore, I can't imagine there's any way to guess what server/port the next actual request might come in on. You have to so it on Begin_Session.

由于在应用程序启动期间管道中不再存在请求上下文,我无法想象有什么方法可以猜测下一个实际请求可能会出现在哪个服务器/端口上。你必须在Begin_Session中这么做。

Here's what I'm using when not in Classic Mode. The overhead is negligible.

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

/// <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 + "/");
                _init = true;
            }
        }
    }
}

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

#5


5  

Based on OP detailed needs explained in comments, a more appropriate solution exists. The OP states he wishes to add custom data in its logs with log4net, data related to requests.

根据OP中详细的需求,有一个更合适的解决方案。OP声明他希望在日志中添加与请求相关的log4net自定义数据。

Rather than wrapping each log4net call into a custom centralized log call which handles retrieving request related data (on each log call), log4net features context dictionaries for setting up custom additional data to log. Using those dictionnaries allows to position your request log data for current request at BeginRequest event, then to dismiss it at EndRequest event. Any log in between will benefit from those custom data.

log4net没有将每个log4net调用封装到一个自定义集中的日志调用中,该调用处理检索请求相关的数据(在每个日志调用上),而是使用上下文字典来设置要记录的自定义附加数据。使用这些字典可以在BeginRequest事件中定位请求日志数据,然后在EndRequest事件中取消它。中间的任何日志都将受益于这些自定义数据。

And things that do not happen in a request context will not try to log request related data, eliminating the need to test for request availability. This solution matches the principle Arman McHitaryan was suggesting in his answer.

在请求上下文中没有发生的事情不会尝试记录请求相关的数据,从而消除了测试请求可用性的需要。这个解决方案符合Arman McHitaryan在他的回答中提出的原则。

For this solution to work, you will also need some additional configuration on your log4net appenders in order for them to log your custom data.

要使这个解决方案有效,您还需要log4net appender上的一些附加配置,以便它们记录您的自定义数据。

This solution can be easily implemented as a custom log enhancement module. Here is sample code for it:

这个解决方案可以作为自定义日志增强模块轻松实现。下面是它的示例代码:

using System;
using System.Web;
using log4net;
using log4net.Core;

namespace YourNameSpace
{
    public class LogHttpModule : IHttpModule
    {
        public void Dispose()
        {
            // nothing to free
        }

        private const string _ipKey = "IP";
        private const string _urlKey = "URL";
        private const string _refererKey = "Referer";
        private const string _userAgentKey = "UserAgent";
        private const string _userNameKey = "userName";

        public void Init(HttpApplication context)
        {
            context.BeginRequest += WebAppli_BeginRequest;
            context.PostAuthenticateRequest += WebAppli_PostAuthenticateRequest;
            // All custom properties must be initialized, otherwise log4net will not get
            // them from HttpContext.
            InitValueProviders(_ipKey, _urlKey, _refererKey, _userAgentKey,
                _userNameKey);
        }

        private void InitValueProviders(params string[] valueKeys)
        {
            if (valueKeys == null)
                return;
            foreach(var key in valueKeys)
            {
                GlobalContext.Properties[key] = new HttpContextValueProvider(key);
            }
        }

        private void WebAppli_BeginRequest(object sender, EventArgs e)
        {
            var currContext = HttpContext.Current;
            currContext.Items[_ipKey] = currContext.Request.UserHostAddress;
            currContext.Items[_urlKey] = currContext.Request.Url.AbsoluteUri;
            currContext.Items[_refererKey] = currContext.Request.UrlReferrer != null ? 
                currContext.Request.UrlReferrer.AbsoluteUri : null;
            currContext.Items[_userAgentKey] = currContext.Request.UserAgent;
        }

        private void WebAppli_PostAuthenticateRequest(object sender, EventArgs e)
        {
            var currContext = HttpContext.Current;
            // log4net doc states that %identity is "extremely slow":
            // http://logging.apache.org/log4net/release/sdk/log4net.Layout.PatternLayout.html
            // So here is some custom retrieval logic for it, so bad, especialy since I
            // tend to think this is a missed copy/paste in that documentation.
            // Indeed, we can find by inspection in default properties fetch by log4net a
            // log4net:Identity property with the data, but it looks undocumented...
            currContext.Items[_userNameKey] = currContext.User.Identity.Name;
        }
    }

    // General idea coming from 
    // http://piers7.blogspot.fr/2005/12/log4net-context-problems-with-aspnet.html
    // We can not use log4net ThreadContext or LogicalThreadContext with asp.net, since
    // asp.net may switch thread while serving a request, and reset the call context
    // in the process.
    public class HttpContextValueProvider : IFixingRequired
    {
        private string _contextKey;
        public HttpContextValueProvider(string contextKey)
        {
            _contextKey = contextKey;
        }

        public override string ToString()
        {
            var currContext = HttpContext.Current;
            if (currContext == null)
                return null;
            var value = currContext.Items[_contextKey];
            if (value == null)
                return null;
            return value.ToString();
        }

        object IFixingRequired.GetFixedObject()
        {
            return ToString();
        }
    }
}

Add it to your site, IIS 7+ conf sample:

将其添加到您的站点,IIS 7+ conf示例:

<system.webServer>
  <!-- other stuff removed ... -->
  <modules>
    <!-- other stuff removed ... -->
    <add name="LogEnhancer" type="YourNameSpace.LogHttpModule, YourAssemblyName" preCondition="managedHandler" />
    <!-- other stuff removed ... -->
  </modules>
  <!-- other stuff removed ... -->
</system.webServer>

And set up appenders to log those additional properties, sample config:

并设置appenders来记录这些附加属性,示例配置:

<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <!-- other stuff removed ... -->
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message - %property%newline%exception" />
    </layout>
  </appender>
  <appender name="SqlAppender" type="log4net.Appender.AdoNetAppender">
    <!-- other stuff removed ... -->
    <commandText value="INSERT INTO YourLogTable ([Date],[Thread],[Level],[Logger],[UserName],[Message],[Exception],[Ip],[Url],[Referer],[UserAgent]) VALUES (@log_date, @thread, @log_level, @logger, @userName, @message, @exception, @Ip, @Url, @Referer, @UserAgent)" />
    <!-- other parameters removed ... -->
    <parameter>
      <parameterName value="@userName" />
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%property{userName}" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@Ip"/>
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%property{Ip}" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@Url"/>
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%property{Url}" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@Referer"/>
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%property{Referer}" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@UserAgent"/>
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%property{UserAgent}" />
      </layout>
    </parameter>
  </appender>
  <!-- other stuff removed ... -->
</log4net>

#6


1  

You can get around the problem without switching to classic mode and still use Application_Start

不用切换到经典模式,也可以使用Application_Start来解决这个问题

public class Global : HttpApplication
{
   private static HttpRequest initialRequest;

   static Global()
   {
      initialRequest = HttpContext.Current.Request;       
   }

   void Application_Start(object sender, EventArgs e)
   {
      //access the initial request here
   }

For some reason, the static type is created with a request in its HTTPContext, allowing you to store it and reuse it immediately in the Application_Start event

出于某种原因,静态类型是在其HTTPContext中创建的,允许您将其存储并立即在Application_Start事件中重用

#7


1  

I was able to solve this problem by moving in to "Classic" mode from "integrated" mode.

我可以通过从“集成”模式进入“经典”模式来解决这个问题。

#8


-3  

You can use following:

您可以使用:

    protected void Application_Start(object sender, EventArgs e)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(StartMySystem));
    }

    private void StartMySystem(object state)
    {
        Log(HttpContext.Current.Request.ToString());
    }

#9


-4  

do this in global.asax.cs:

在global.asax.cs这样做:

protected void Application_Start()
{
  //string ServerSoftware = Context.Request.ServerVariables["SERVER_SOFTWARE"];
  string server = Context.Request.ServerVariables["SERVER_NAME"];
  string port = Context.Request.ServerVariables["SERVER_PORT"];
  HttpRuntime.Cache.Insert("basePath", "http://" + server + ":" + port + "/");
  // ...
}

works like a charm. this.Context.Request is there...

就像一个魅力。this.Context。请求有…

this.Request throws exception intentionally based on a flag

这一点。请求基于一个标志故意抛出异常

#1


69  

Please see IIS7 Integrated mode: Request is not available in this context exception in Application_Start:

请参见IIS7集成模式:请求在Application_Start的此上下文异常中不可用:

The “Request is not available in this context” exception is one of the more common errors you may receive on when moving ASP.NET applications to Integrated mode on IIS 7.0. This exception happens in your implementation of the Application_Start method in the global.asax file if you attempt to access the HttpContext of the request that started the application.

“请求在此上下文中不可用”异常是您在移动ASP时可能遇到的最常见错误之一。NET应用程序集成模式在IIS 7.0。在全局的Application_Start方法的实现中发生了这个异常。如果您试图访问启动应用程序的请求的HttpContext,请使用asax文件。

#2


37  

When you have custom logging logic, it is rather annoying to be forced either not to log application_start or to have to let an exception occurs in the logger (even if handled).

当您有自定义日志记录逻辑时,强制不记录application_start或必须让日志记录器中发生异常(即使已处理)是相当烦人的。

It appears that rather than testing for Request availability, you can test for Handler availability: when there is no Request, it would be strange to still have a request handler. And testing for Handler does not raise that dreaded Request is not available in this context exception.

与测试请求可用性不同,您可以测试处理程序的可用性:当没有请求时,仍然有一个请求处理程序是奇怪的。并且,对Handler的测试不会引发这个上下文异常中不可用的可怕请求。

So you may change your code to:

因此,您可以将代码更改为:

var currContext = HttpContext.Current;
if (currContext != null && currContext.Handler != null)

Beware, in the context of an http module, Handler may not be defined though Request and Response are defined (I have seen that in BeginRequest event). So if you need request/response logging in a custom http module, my answer may not be suitable.

注意,在http模块的上下文中,可能没有通过定义请求和响应来定义处理程序(我在BeginRequest事件中见过)。因此,如果需要在自定义http模块中进行请求/响应日志记录,我的回答可能不太合适。

#3


13  

This is very classic case: If you end up having to check for any data provided by the http instance then consider moving that code under the BeginRequest event.

这是非常典型的情况:如果您最终不得不检查http实例提供的任何数据,那么请考虑在BeginRequest事件下移动该代码。

void Application_BeginRequest(Object source, EventArgs e)

This is the right place to check for http headers, query string and etc... Application_Start is for the settings that apply for the application entire run time, such as routing, filters, logging and so on.

这是检查http头、查询字符串等的正确位置。Application_Start用于应用程序整个运行时的设置,例如路由、过滤器、日志记录等等。

Please, don't apply any workarounds such as static .ctor or switching to the Classic mode unless there's no way to move the code from the Start to BeginRequest. that should be doable for the vast majority of your cases.

请不要应用任何变通方法,例如静态.ctor或切换到经典模式,除非没有办法将代码从开始移动到开始请求。这对你的绝大多数案例都是可行的。

#4


6  

Since there's no Request context in the pipeline during app start anymore, I can't imagine there's any way to guess what server/port the next actual request might come in on. You have to so it on Begin_Session.

由于在应用程序启动期间管道中不再存在请求上下文,我无法想象有什么方法可以猜测下一个实际请求可能会出现在哪个服务器/端口上。你必须在Begin_Session中这么做。

Here's what I'm using when not in Classic Mode. The overhead is negligible.

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

/// <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 + "/");
                _init = true;
            }
        }
    }
}

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

#5


5  

Based on OP detailed needs explained in comments, a more appropriate solution exists. The OP states he wishes to add custom data in its logs with log4net, data related to requests.

根据OP中详细的需求,有一个更合适的解决方案。OP声明他希望在日志中添加与请求相关的log4net自定义数据。

Rather than wrapping each log4net call into a custom centralized log call which handles retrieving request related data (on each log call), log4net features context dictionaries for setting up custom additional data to log. Using those dictionnaries allows to position your request log data for current request at BeginRequest event, then to dismiss it at EndRequest event. Any log in between will benefit from those custom data.

log4net没有将每个log4net调用封装到一个自定义集中的日志调用中,该调用处理检索请求相关的数据(在每个日志调用上),而是使用上下文字典来设置要记录的自定义附加数据。使用这些字典可以在BeginRequest事件中定位请求日志数据,然后在EndRequest事件中取消它。中间的任何日志都将受益于这些自定义数据。

And things that do not happen in a request context will not try to log request related data, eliminating the need to test for request availability. This solution matches the principle Arman McHitaryan was suggesting in his answer.

在请求上下文中没有发生的事情不会尝试记录请求相关的数据,从而消除了测试请求可用性的需要。这个解决方案符合Arman McHitaryan在他的回答中提出的原则。

For this solution to work, you will also need some additional configuration on your log4net appenders in order for them to log your custom data.

要使这个解决方案有效,您还需要log4net appender上的一些附加配置,以便它们记录您的自定义数据。

This solution can be easily implemented as a custom log enhancement module. Here is sample code for it:

这个解决方案可以作为自定义日志增强模块轻松实现。下面是它的示例代码:

using System;
using System.Web;
using log4net;
using log4net.Core;

namespace YourNameSpace
{
    public class LogHttpModule : IHttpModule
    {
        public void Dispose()
        {
            // nothing to free
        }

        private const string _ipKey = "IP";
        private const string _urlKey = "URL";
        private const string _refererKey = "Referer";
        private const string _userAgentKey = "UserAgent";
        private const string _userNameKey = "userName";

        public void Init(HttpApplication context)
        {
            context.BeginRequest += WebAppli_BeginRequest;
            context.PostAuthenticateRequest += WebAppli_PostAuthenticateRequest;
            // All custom properties must be initialized, otherwise log4net will not get
            // them from HttpContext.
            InitValueProviders(_ipKey, _urlKey, _refererKey, _userAgentKey,
                _userNameKey);
        }

        private void InitValueProviders(params string[] valueKeys)
        {
            if (valueKeys == null)
                return;
            foreach(var key in valueKeys)
            {
                GlobalContext.Properties[key] = new HttpContextValueProvider(key);
            }
        }

        private void WebAppli_BeginRequest(object sender, EventArgs e)
        {
            var currContext = HttpContext.Current;
            currContext.Items[_ipKey] = currContext.Request.UserHostAddress;
            currContext.Items[_urlKey] = currContext.Request.Url.AbsoluteUri;
            currContext.Items[_refererKey] = currContext.Request.UrlReferrer != null ? 
                currContext.Request.UrlReferrer.AbsoluteUri : null;
            currContext.Items[_userAgentKey] = currContext.Request.UserAgent;
        }

        private void WebAppli_PostAuthenticateRequest(object sender, EventArgs e)
        {
            var currContext = HttpContext.Current;
            // log4net doc states that %identity is "extremely slow":
            // http://logging.apache.org/log4net/release/sdk/log4net.Layout.PatternLayout.html
            // So here is some custom retrieval logic for it, so bad, especialy since I
            // tend to think this is a missed copy/paste in that documentation.
            // Indeed, we can find by inspection in default properties fetch by log4net a
            // log4net:Identity property with the data, but it looks undocumented...
            currContext.Items[_userNameKey] = currContext.User.Identity.Name;
        }
    }

    // General idea coming from 
    // http://piers7.blogspot.fr/2005/12/log4net-context-problems-with-aspnet.html
    // We can not use log4net ThreadContext or LogicalThreadContext with asp.net, since
    // asp.net may switch thread while serving a request, and reset the call context
    // in the process.
    public class HttpContextValueProvider : IFixingRequired
    {
        private string _contextKey;
        public HttpContextValueProvider(string contextKey)
        {
            _contextKey = contextKey;
        }

        public override string ToString()
        {
            var currContext = HttpContext.Current;
            if (currContext == null)
                return null;
            var value = currContext.Items[_contextKey];
            if (value == null)
                return null;
            return value.ToString();
        }

        object IFixingRequired.GetFixedObject()
        {
            return ToString();
        }
    }
}

Add it to your site, IIS 7+ conf sample:

将其添加到您的站点,IIS 7+ conf示例:

<system.webServer>
  <!-- other stuff removed ... -->
  <modules>
    <!-- other stuff removed ... -->
    <add name="LogEnhancer" type="YourNameSpace.LogHttpModule, YourAssemblyName" preCondition="managedHandler" />
    <!-- other stuff removed ... -->
  </modules>
  <!-- other stuff removed ... -->
</system.webServer>

And set up appenders to log those additional properties, sample config:

并设置appenders来记录这些附加属性,示例配置:

<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <!-- other stuff removed ... -->
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message - %property%newline%exception" />
    </layout>
  </appender>
  <appender name="SqlAppender" type="log4net.Appender.AdoNetAppender">
    <!-- other stuff removed ... -->
    <commandText value="INSERT INTO YourLogTable ([Date],[Thread],[Level],[Logger],[UserName],[Message],[Exception],[Ip],[Url],[Referer],[UserAgent]) VALUES (@log_date, @thread, @log_level, @logger, @userName, @message, @exception, @Ip, @Url, @Referer, @UserAgent)" />
    <!-- other parameters removed ... -->
    <parameter>
      <parameterName value="@userName" />
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%property{userName}" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@Ip"/>
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%property{Ip}" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@Url"/>
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%property{Url}" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@Referer"/>
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%property{Referer}" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@UserAgent"/>
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%property{UserAgent}" />
      </layout>
    </parameter>
  </appender>
  <!-- other stuff removed ... -->
</log4net>

#6


1  

You can get around the problem without switching to classic mode and still use Application_Start

不用切换到经典模式,也可以使用Application_Start来解决这个问题

public class Global : HttpApplication
{
   private static HttpRequest initialRequest;

   static Global()
   {
      initialRequest = HttpContext.Current.Request;       
   }

   void Application_Start(object sender, EventArgs e)
   {
      //access the initial request here
   }

For some reason, the static type is created with a request in its HTTPContext, allowing you to store it and reuse it immediately in the Application_Start event

出于某种原因,静态类型是在其HTTPContext中创建的,允许您将其存储并立即在Application_Start事件中重用

#7


1  

I was able to solve this problem by moving in to "Classic" mode from "integrated" mode.

我可以通过从“集成”模式进入“经典”模式来解决这个问题。

#8


-3  

You can use following:

您可以使用:

    protected void Application_Start(object sender, EventArgs e)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(StartMySystem));
    }

    private void StartMySystem(object state)
    {
        Log(HttpContext.Current.Request.ToString());
    }

#9


-4  

do this in global.asax.cs:

在global.asax.cs这样做:

protected void Application_Start()
{
  //string ServerSoftware = Context.Request.ServerVariables["SERVER_SOFTWARE"];
  string server = Context.Request.ServerVariables["SERVER_NAME"];
  string port = Context.Request.ServerVariables["SERVER_PORT"];
  HttpRuntime.Cache.Insert("basePath", "http://" + server + ":" + port + "/");
  // ...
}

works like a charm. this.Context.Request is there...

就像一个魅力。this.Context。请求有…

this.Request throws exception intentionally based on a flag

这一点。请求基于一个标志故意抛出异常