在此上下文中不提供请求

时间:2010-03-25 17:48:40

标签: asp.net iis-7

我正在运行IIS 7集成模式,我正在

请求在此上下文中不可用

当我尝试在从Application_Start调用的Log4Net相关函数中访问它时。这是我已经

的代码行
if (HttpContext.Current != null && HttpContext.Current.Request != null)

并且正在抛出异常以进行第二次比较。

除了检查HttpContext.Current.Request for null ??

之外,我还能检查什么

发布类似的问题@ Request is not available in this context exception when runnig mvc on iis7.5

但也没有相关的答案。

11 个答案:

答案 0 :(得分:73)

请参阅IIS7 Integrated mode: Request is not available in this context exception in Application_Start

  

“请求不在此处   上下文“例外是其中之一   您可能会收到的常见错误   将ASP.NET应用程序移动到   IIS 7.0上的集成模式。这个   异常发生在你的   实施   Application_Start方法中的   global.asax文件,如果您尝试   访问请求的HttpContext   这启动了申请。

答案 1 :(得分:40)

当你有自定义日志记录逻辑时,强迫要么不记录application_start或者必须让记录器中发生异常(即使已经处理)也很烦人。

似乎不是测试Request可用性,而是可以测试Handler可用性:当没有Request时,仍然有一个请求处理程序会很奇怪。对Handler进行测试不会引起可怕的Request is not available in this context异常。

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

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

请注意,在http模块的上下文中,虽然HandlerRequest已定义(我在BeginRequest事件中已经看到),但可能无法定义Response。因此,如果您需要在自定义http模块中记录请求/响应,我的答案可能不合适。

答案 2 :(得分:17)

这是非常经典的案例:如果您最终必须检查http实例提供的任何数据,请考虑在BeginRequest事件下移动该代码。

void Application_BeginRequest(Object source, EventArgs e)

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

请不要应用任何变通办法,例如static .ctor或切换到经典模式,除非无法从Start移动代码到BeginRequest。对于绝大多数情况来说应该是可行的。

答案 3 :(得分:6)

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

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

/// <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);
}

答案 4 :(得分:6)

根据评论中解释的OP详细需求,存在更合适的解决方案。 OP声明他希望在日志中使用log4net添加自定义数据,这些数据与请求相关。

log4net不是将每个log4net调用包装到处理检索请求相关数据的自定义集中式日志调用中(在每次日志调用中),而是使用上下文字典来设置要记录的自定义附加数据。使用这些字典允许在BeginRequest事件中为当前请求定位请求日志数据,然后在EndRequest事件中将其关闭。任何登录都将受益于这些自定义数据。

在请求上下文中不会发生的事情不会尝试记录请求相关数据,从而无需测试请求可用性。这个解决方案符合Arman McHitaryan在answer中建议的原则。

要使此解决方案正常工作,您还需要在log4net appender上进行一些额外配置,以便他们记录您的自定义数据。

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

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();
        }
    }
}

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

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

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

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

答案 5 :(得分:2)

您可以在不切换到经典模式的情况下解决问题并仍然使用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
   }

出于某种原因,在HTTPContext中使用请求创建静态类型,允许您存储它并在Application_Start事件中立即重用它

答案 6 :(得分:1)

我能够通过转入&#34; Classic&#34;来解决/解决这个问题。模式来自&#34;集成&#34;模式。

答案 7 :(得分:0)

这对我有用-如果您必须登录Application_Start,请在修改上下文之前进行操作。您将获得一个日志条目,没有任何来源,例如:

2019-03-12 09:35:43,659信息(空)-应用程序已启动

我通常同时登录Application_Start和Session_Start,所以我在下一条消息中会看到更多详细信息

2019-03-12 09:35:45,064 INFO〜/ Leads / Leads.aspx-会话已开始(本地)

        protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();
            log.Info("Application Started");
            GlobalContext.Properties["page"] = new GetCurrentPage();
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Globals._Environment = WebAppConfig.getEnvironment(Request.Url.AbsoluteUri, Properties.Settings.Default.LocalOverride);
            log.Info(string.Format("Session Started ({0})", Globals._Environment));
        }


答案 8 :(得分:0)

在Visual Studio 2012中,当我错误地使用“ debug”选项发布解决方案时,出现了此异常。使用“释放”选项,它从未发生。希望对您有所帮助。

答案 9 :(得分:-3)

您可以使用以下内容:

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

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

答案 10 :(得分:-4)

在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 + "/");
  // ...
}

就像一个魅力。 this.Context.Request就在那里......

this.Request根据标志

故意抛出异常
相关问题