Request is not available in this context - asp.net

I'm running IIS 7 Integrated mode and I'm getting
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
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??
A similar question is posted #
Request is not available in this context exception when runnig mvc on iis7.5
but no relevant answer there either.

Please see IIS7 Integrated mode: Request is not available in this context exception in 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.

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).
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.
So you may change your code to:
var currContext = HttpContext.Current;
if (currContext != null && currContext.Handler != null)
Beware, in the context of a 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.

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

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

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.
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 these custom data.
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.
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.
This solution can be easily implemented as a custom log enhancement module. Here is some 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+ configuration 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>
And set up appenders to log those additional properties, sample config:
<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>

You can get around the problem without switching to classic mode and still use 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

This worked for me - if you have to log in Application_Start, do it before you modify the context. You will get a log entry, just with no source, like:
2019-03-12 09:35:43,659 INFO (null) - Application Started
I generally log both the Application_Start and Session_Start, so I see more detail in the next message
2019-03-12 09:35:45,064 INFO ~/Leads/Leads.aspx - Session Started (Local)
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));
}

I was able to workaround/hack this problem by moving in to "Classic" mode from "integrated" mode.

In visual studio 2012, When I published the solution mistakenly with 'debug' option I got this exception. With 'release' option it never occurred. Hope it helps.

Set application pool to .NET v4.5 Classic

public bool StartVideo(byte channel)
{
try
{
CommandObject command = new CommandObject(Commands.START_VIDEO, new byte[] {channel}, channel);
m_ResponseEvent.Reset();
lock (m_Commands)
{
m_Commands.Enqueue(command);
}
if (m_ResponseEvent.WaitOne(5000, true))
{
return m_Response == null ? false : true;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return false;
}

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

do this in 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.Request throws exception intentionally based on a flag

Related

ASP.NET HttpModule Request handling

I would like to handle static file web requests through an HttpModule to show the documents in my CMS according to some policies. I can filter out a request, but I don't know how to directly process such a request as asp.net should do.
Is this what you're looking for? Assuming you're running in integrated pipeline mode, all requests should make it through here, so you can kill the request if unauthorized, or let it through like normal otherwise.
public class MyModule1 : IHttpModule
{
public void Dispose() {}
public void Init(HttpApplication context)
{
context.AuthorizeRequest += context_AuthorizeRequest;
}
void context_AuthorizeRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
// Whatever you want to test to see if they are allowed
// to access this file. I believe the `User` property is
// populated by this point.
if (app.Context.Request.QueryString["allow"] == "1")
{
return;
}
app.Context.Response.StatusCode = 401;
app.Context.Response.End();
}
}
<configuration>
<system.web>
<httpModules>
<add name="CustomSecurityModule" type="MyModule1"/>
</httpModules>
</system.web>
</configuration>

Health Monitoring is not logging errors when CustomError is set to "On" or "RemoteOnly"

I am using Health Monitoring for catching all errors and sending them to email. While it works in the development environment it did not when I deploy it in Prod. The only difference being the "customerrors" set to "on/off". So, I verified it again and it seems it will not log when the custom errors is set to "On/RemoteOnly". Below is part of my configuration in question.
Is there a workaround to this issue? Thanks.
<healthMonitoring enabled="true">
<eventMappings>
<clear />
<add name="All Errors" type="System.Web.Management.WebBaseErrorEvent"
startEventCode="0" endEventCode="2147483647" />
</eventMappings>
<providers>
<clear />
<add
name="SimpleMailWebEventProvider"
type="System.Web.Management.SimpleMailWebEventProvider"
to="dev#net"
from="de#net"
buffer="false"
/>
</providers>
<rules>
<clear />
<add name="All Errors Default" eventName="All Errors" provider="SimpleMailWebEventProvider"
profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" />
</rules>
</healthMonitoring>
--update
This is MVC3 project
In an ASP.NET MVC 3 project you will have a global HandleError action filter registered by default in global.asax.cs:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
This attribute gets applied to every controller action and if customErrors are set to On only the custom error page is displayed and the exception that occured in a controller action is marked as handled. ASP.NET Health Monitoring doesn't see this exception anymore and can't log it.
An approach to use Health Monitoring together with the HandleError attribute and a custom error page is described here and here and here:
You create a custom error attribute derived from HandleError:
public class HandleErrorHealthMonitoringAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
// Do the default, i.e. show custom error page if custom errors are on
base.OnException(filterContext);
// Suppress raising the health monitoring event below if custom errors
// are off. In that case health monitoring will receive the exception
// anyway and raise the event
if (!filterContext.HttpContext.IsCustomErrorEnabled)
return;
// Raise health monitoring event
var errorEvent = new GenericWebRequestErrorEvent(
"Unhandled exception occurred.", this,
WebEventCodes.WebExtendedBase + 1, filterContext.Exception);
errorEvent.Raise();
}
}
And then register this attribute instead of default HandleError:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorHealthMonitoringAttribute());
}
The GenericWebRequestErrorEvent is a custom error event derived from the base WebRequestErrorEvent. It doesn't do anything custom and only exists because WebRequestErrorEvent doesn't have any public constructors, so we can't use var errorEvent = new WebRequestErrorEvent(...):
public class GenericWebRequestErrorEvent : WebRequestErrorEvent
{
public GenericWebRequestErrorEvent(string message, object eventSource,
int eventCode, Exception exception) :
base(message, eventSource, eventCode, exception)
{
}
public GenericWebRequestErrorEvent(string message, object eventSource,
int eventCode, int eventDetailCode, Exception exception) :
base(message, eventSource, eventCode, eventDetailCode, exception)
{
}
}
Note, that you will receive an email titled with MyNamespace.GenericWebRequestErrorEvent and not with System.Web.Management.WebRequestErrorEvent and the event code will always be 100001 (= WebEventCodes.WebExtendedBase + 1).

How do I get log4net to decrypt an encrypted connection string from the web.config?

The web application I'm working on uses log4net for logging. A requirement of the project is that the connections strings should be encrypted. How do I tell log4net to use the decrypted value?
For example:
<log4net>
<root>
<level value="Debug"/>
<appender-ref ref="AdoNetAppender"/>
</root>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1"/>
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<connectionString value="encryptedconnectionstringhere=="/>
Is there a way to accomplish this?
When implementing drumboog's answer, I ran into stackoverflow exceptions due to an infinitely recursive method call. This is essentially what I ended up using.
public class CustomAdoNetAppender : AdoNetAppender
{
private string _connectionString;
protected override string ResolveConnectionString(out string connectionStringContext)
{
if(string.IsNullOrEmpty(_connectionString))
{
var decrypt = new MyDecyptionLib();
_connectionString = decrypt.MyDecryptionFunction(ConfigurationManager.AppSettings["Connection"]);
}
connectionStringContext = _connectionString;
return connectionStringContext;
}
}
...and in the log4net config section
<appender name="AdoNetAppender" type="My.Name.Space.To.CustomAdoNetAppender">
Aside from writing a custom appender, you could encrypt the entire configuration section:
http://msdn.microsoft.com/en-us/library/zhhddkxy.aspx
Programmatically encrypting a config-file in .NET
Edit:
log4net is open source, so you can also try looking through their code and customizing their appender to fit your needs... maybe something like this:
public class DecryptConnectionStringAdoNetAppender : AdoNetAppender
{
protected override string ResolveConnectionString(out string connectionStringContext)
{
string result = base.ResolveConnectionString(out connectionStringContext);
if (String.IsNullOrEmpty(result))
{
return result;
}
else
{
Decrypt(result);
}
}
private string Decrypt(string encryptedValue)
{
// Your code goes here.
}
}
Then update the type attribute of the appender element in the config file:
<appender name="AdoNetAppender" type="Your.Namespace.DecryptConnectionStringAdoNetAppender">

IIS7 Module Only Works First Time?

I create an IIS Module that appends text to the page before it loads. When I go to the URL, this works perfect the first time the page loads. On subsequent loads, however, the text is never appended.
Any thoughts on how to remedy this?
== CODE ==
Here's my web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<system.webServer>
<modules>
<add name="MIModule" type="MI.MyModule, MI" />
</modules>
<caching enabled="false" enableKernelCache="false" />
</system.webServer>
</configuration>
Some module code:
public void context_PreRequestHandlerExecute(Object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpRequest request = app.Context.Request;
string pageContent = app.Response.Output.ToString();
string useragent = "HI!<br />" + pageContent + "<hr />" ;
try
{
_current.Response.Output.Write(useragent);
}
catch
{
}
}
and the rest of the code:
private HttpContext _current = null;
#region IHttpModule Members
public void Dispose()
{
throw new Exception("Not implemented");
}
public void Init(HttpApplication context)
{
_current = context.Context;
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}
#endregion
Is the _current variable actually HttpContext.Current? Is it a static field in your module? When/how is it initialized? My guess is that the empty catch clause gobbles up all errors, and following that thought, you most probably get a null reference on _current. Try removing the try/catch to learn more on what's wrong with your code

How to debug UrlRewriter.NET?

I have looked at their help page it seems like I can register a debug logger that outputs information to the 'standard ASP.NET debug window'. My problem is I don't know what that means, if it means the debug output window in Visual Studio (where you see build output, debug output and more) I am not seeing any UrlRewriter debug output.
The rules are working (mostly) I just want to get more debug output to fix issues.
I added the register call to the rewriter section like this:
<rewriter>
<register logger="Intelligencia.UrlRewriter.Logging.DebugLogger, Intelligencia.UrlRewriter" />
....
</rewriter>
I am hosting this website locally in IIS on Vista, to debug it I attach the debugger to the w3wp process.
Other selected parts from the web.config"
<compilation debug="true">
<assemblies>
...
</assemblies>
</compilation>
<trace enabled="true"/>
Where should I see the debug output from UrlRewriter.NET? If it is in the Visual Studio debug output window, any ideas why I am not seeing it there?
Try to run the DebugView for read the messages from Intelligencia.UrlRewriter
Get it from here
http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx
I see the source code, and I belive thats works, but if not works, then why not get the source code, and compile it with your project and just debug it on site ?
I wanted to debug because I had the impression my rewrite rules weren't functioning.
After a while I figured out I had to alter my web.config and add the following line to the 'system.web', 'httpModules' section:
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter"/>
For anyone who wants to log the event messages to a file as well as see them in the debug output window, here's a piece of code I created.
Please only use this in a development environment, this code is not optimized.
usage:
In your asp.net application, add a reference to this library (MyPresentationLayer.Web).
Add the following element to 'rewriter' node:
<register logger="IntelligenciaExt.Web.Logging.UrlRewriterIntelligencia.FileLogger, IntelligenciaExt.Web"/>
By default the log file can be found outside your 'www' folder, in the subfolder 'intelligenciaLog'.
using System;
using SysDiag = System.Diagnostics;
using System.IO;
using Intelligencia.UrlRewriter.Logging;
namespace MyPresentationLayer.Web.Logging.UrlRewriterIntelligencia
{
/// <summary>
/// Custom logger for Intelligencia UrlRewriter.net that logs messages
/// to a plain text file (../intelligenciaLog/log.txt).
/// </summary>
public class FileLogger : IRewriteLogger
{
private const string _logFolderName = "../intelligenciaLog";
private const string _logFileName = "log.txt";
private const string _appName = "UrlRewriterIntelligencia.FileLogger";
public FileLogger()
{
LogToFile(Level.Info, "Created new instance of class 'FileLogger'");
}
public void Debug(object message)
{
LogToFile(Level.Debug, (string)message);
}
public void Error(object message, Exception exception)
{
string errorMessage = String.Format("{0} ({1})", message, exception);
LogToFile(Level.Error, errorMessage);
}
public void Error(object message)
{
LogToFile(Level.Error, (string)message);
}
public void Fatal(object message, Exception exception)
{
string fatalMessage = String.Format("{0} ({1})", message, exception);
LogToFile(Level.Fatal, fatalMessage);
}
public void Info(object message)
{
LogToFile(Level.Info, (string)message);
}
public void Warn(object message)
{
LogToFile(Level.Warn, (string)message);
}
private static void LogToFile(Level level, string message)
{
string outputMessage = String.Format("[{0} {1} {2}] {3}", DateTime.Now.ToString("yyyyMMdd HH:mm:ss"),
_appName.PadRight(50, ' '), level.ToString().PadRight(5, ' '),
message);
SysDiag.Debug.WriteLine(outputMessage);
try
{
string pathToLogFolder =Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _logFolderName);
if (!Directory.Exists(pathToLogFolder))
{
Directory.CreateDirectory(pathToLogFolder);
}
string fullPathToLogFile = Path.Combine(pathToLogFolder, _logFileName);
using (StreamWriter w = File.AppendText(fullPathToLogFile))
{
w.WriteLine(outputMessage);
// Update the underlying file.
w.Flush(); // Close the writer and underlying file.
w.Close();
}
}
catch (Exception) { }
}
internal enum Level
{
Warn,
Fatal,
Info,
Error,
Debug
}
}
}

Resources