Saturday, September 27, 2008

Writing cookie at SharePoint Application startup

Scenario:
You want to write a Cookie value when SharePoint application is accessed by user.

Solution:
SharePoint being an ASP.Net Application, you can stuff some code in Global.asax file which is location in the WebApplication folder.

Code(Global.asax):

<%@ Assembly Name="Microsoft.SharePoint"%>
<%@ Application Language="C#" Inherits="Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication" %>
<%@ Import Namespace="System.Web" %>

<SCRIPT language="C#" runat="server">
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
try
{
HttpContext ctx = HttpContext.Current;
HttpCookie newCookie = new HttpCookie("LoggedInUser",ctx.User.Identity.Name);
newCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(newCookie);

}
catch (Exception)
{
// Eat the exception so that the site is still usable
// even if the stats go down from some reason.
}
}
</SCRIPT>
Article:
http://msdn.microsoft.com/en-us/library/aa287547(VS.71).aspx

0 comments: