Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 286

Why is session NULL in BeginRequest()? (httpRequestBegin)

$
0
0

Have you ever wondered why the session is NULL when a request begins?
The answer is simple: The Application_BeginRequest() event is fired before the Session_Start() event.
The BeginRequest() event is fired for each request as the first event. The Session_Start() event is only fired once per session, after the BeginRequest() event.

The following is specific for Sitecore:

This means that if you add a new processor in the httpRequestBegin pipeline, you will get an exception if you call HttpContext.Current.Session:

namespace MyNameSpace
{
  class MyFunction : HttpRequestProcessor
  {
    public override void Process(HttpRequestArgs args)
    {
	  // THIS WILL FAIL:
	  var somevar = HttpContext.Current.Session;
    }
  }
}

Simply because the session is not available at the time.

So what do you do then?

Sitecore have added another pipeline, httpRequestProcessed, which is fired AFTER httpRequestBegin AND Session_Start():

<httpRequestProcessed>
  <processor type="MyNamespace.MyFunction, MyDLL" />
</httpRequestProcessed>

This pipeline is usually used for replacing content or setting http status codes after the contents of a website have been processed, but you can use it for any purpose you require.

And please note that the pipeline is called for every request that have ended, so you need the same amount of carefulness as when calling httpRequestBegin. Remember to filter out doublets, Sitecore calls, check for Sitecore context etc., before calling your code.

// This is a classic (maybe a little over-the-top) 
// test to see if the request is a request
// that needs processing
namespace MyNamespace
{
  public class MyClass : HttpRequestProcessor
  {
    public override void Process(HttpRequestArgs args)
    {
      Assert.ArgumentNotNull(args, "args");
      if (Context.Site == null)
        return;
      if (Context.Site.Domain != DomainManager.GetDomain("extranet"))
        return;
      if (args.Url.FilePathWithQueryString.ToUpperInvariant().Contains("redirected=true".ToUpperInvariant()))
        return; // already redirected
      if (Context.PageMode.IsPageEditor)  
	    return;

      // DO CODE
    }
  }
}

MORE TO READ:

 



Viewing all articles
Browse latest Browse all 286

Trending Articles