August 7, 2008

MOSS: Using Session_OnStart

Problem:
Want to do something in Session_OnStart event in your MOSS web application? Modifying global.asax doesn't have any effect? Getting frustrated?

Solution:
No worries, just create HttpModule like in the following example. In my code I'm creating a "WWW" cookie that is required by Load Balancer and setting cookie value from an appSettings key in web.config.

---
class NLBModule : IHttpModule
{
#region IHttpModule Members

public void Dispose()
{}

public void Init(HttpApplication context)
{
SessionStateModule sessionModule = (SessionStateModule)context.Modules["Session"];

sessionModule.Start += delegate(object sender, EventArgs e) { sessionModule_Start(sender, e, context); };
}
#endregion

void sessionModule_Start(object sender, EventArgs e, HttpApplication context)
{
context.Response.Cookies.Add(new HttpCookie("WWW", ConfigurationManager.AppSettings["NLB_ID"]));
}
}
---

Finally register the HttpModule in web.config like this:

<system.web>

<httpModules>

<add name="NLBModule" type="MyProject.HttpHandlers.NLBModule, MyProject.HttpHandlers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=XYZ" />

</httpModules>

</system.web>

No comments:

Post a Comment