Tuesday, July 20, 2010

Changing redirection in SharePoint with HttpModule and HttpHandler !

Hi all,

SharePoint is maintaining some redirection by it’s on like error page, by clicking on user or group it will redirect to profile page and so many other…

In one of our requirement we have to implement custom profile page and custom error page.

So for this we need to over ride default SharePoint navigation.

And that can be implemented using HttpModule and HttpHandler.

To know the concept of HttpModule and HttpHander here is great article from Gustavo Velez

So here we go for changing Error page (check comments between the code for understanding)

class RedirectErrorModule : IHttpModule

//Custom error page relative URL
const string errorUrl = "/_layouts/CustomForder/CustomError.aspx";

// implement dispose method to dispose used object
public void Dispose()
//dispose you objects

public void Init(HttpApplication context)
//Define event for application error so that you can override.
context.Error += new EventHandler(context_Error);

//implement error event
void context_Error(object sender, EventArgs e)
string strURL = string.Empty;

//Current site URL
string strSiteURL = SPContext.Current.Site.Url;

//Current web url
string strWebURL = SPContext.Current.Web.Url;

//Clearing context error

//Clearing the response

//redirecting to our custom error page.
HttpContext.Current.Response.Redirect(strWebURL + errorUrl, false);


After doing this we need to add entry in web.config for the same.

Enter following tag in <httpModules> section of your web.config
<add name="CustomHttpModule" type="<<Full assembly name with class>>" />

Check syntax from existing tags from web.config.

The same way we can implement any redirection with the use of end request Event.
public void Init(HttpApplication context)
//end request handler
context.EndRequest += new EventHandler(context_EndRequest);

//End request implementation
void context_EndRequest(object sender, EventArgs e)
HttpApplication httpApp = sender as HttpApplication;
HttpContext context = httpApp.Context;
string httpUrl = context.Request.Url.ToString();
string strWebURL = string.Empty;
string struserID = string.Empty;
//compare your URL and redirect it to custom one
// this is example to redirecting userdisp page (profile page) to custom page.
if (httpUrl.ToLower().Contains("/_layouts/userdisp.aspx"))

//implement business logic and generate url if needed
HttpContext.Current.Response.Redirect(<<Custom URL>>);


And same can be incorporated in one class no need to create another one.

And remember in web.config enter your module at the end after all SharePoint’s event handler so it will not create any problem. There is not at all problem if you write it before SharePoint’s but better to play safe :)

No comments:

Post a Comment