Ads

Thursday, 4 April 2013

control & change the redirection in SharePoint with HttpModule and HttpHandler

In SharePoint some redirection are default like error page, by clicking on user or group it will redirect to profile page and so many other…If you create any custom error page or profile page then you need to over ride default SharePoint navigation.

This 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
HttpContext.Current.Server.ClearError();

//Clearing the response
HttpContext.Current.Response.Clear();

//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.Server.ClearError();
HttpContext.Current.Response.Clear();
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

Ads