using System; using System.Collections.Generic; using System.Text; using System.Web; using Microsoft.SharePoint; using System.IO; using Microsoft.SharePoint.Utilities; namespace SharePointProducts.ActionRedirect { public class RedirectHandler : IHttpHandler { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; string url = request.QueryString["url"]; if (!String.IsNullOrEmpty(url)) { Redirect(context, url); } } private void Redirect(HttpContext context, string url) { SPSite site = null; SPWeb web = null; SPList list = null; SPListItem item = null; try { // Find list item from URL Uri uri = new Uri(url); site = new SPSite(url); site.CatchAccessDeniedException = false; web = site.OpenWeb(); item = web.GetListItem(uri.PathAndQuery); list = item.ParentList; // Assemble server relative redirect URL string defaultViewUrl = list.DefaultViewUrl; int filenameIndex = defaultViewUrl.LastIndexOf('/'); string formUrl = defaultViewUrl.Substring(0, filenameIndex + 1); formUrl += "DispForm.aspx?ID=" + item.ID; // Add RootFolder parameter to the redirect URL string folderUrl = web.ServerRelativeUrl; if (!folderUrl.EndsWith("/")) folderUrl += "/"; folderUrl += item.Url; filenameIndex = folderUrl.LastIndexOf('/'); folderUrl = folderUrl.Substring(0, filenameIndex); formUrl += "&RootFolder=" + SPEncode.UrlEncode(folderUrl); // Add Source parameter to the redirect URL string sourceUrl = uri.GetLeftPart(UriPartial.Authority); sourceUrl += folderUrl; formUrl += "&Source=" + SPEncode.UrlEncode(sourceUrl); // Convert the server relative redirect URL to an absolute URL string newUrl = uri.GetLeftPart(UriPartial.Authority); newUrl += formUrl; context.Response.Redirect(newUrl, true); } finally { if (web != null) web.Dispose(); if (site != null) site.Dispose(); } } } }