I have accomplished this before using HttpHandlers by adding tags to web.xml accordingly. I might as well copy the code here..
private readonly string[] SupportedExtensions = new[] { "*.docx", ".pptx", "xlsx" };
private void AddForSharePoint2007()
{
// SP2007 uses IIS6.0 compatibility mode
SPWebService contentService = SPWebService.ContentService;
// the Name must be XPATH of Value.. otherwise SP wont remove!
SPWebConfigModification item = new SPWebConfigModification
{
Owner = FeatureId,
Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode,
Path = "/configuration/system.web/httpHandlers",
Name = "add[@verb=\"*\"][@path=\"" + string.Join(",", SupportedExtensions) + "\"][@type=\"MyNamespace.DownloadHandler, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=*****\"]",
Value = "<add verb=\"*\" path=\"" + string.Join(",", SupportedExtensions) + "\" type=\"MyNamespace.DownloadHandler, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=******\"/>"
};
contentService.WebConfigModifications.Add(item);
contentService.Update();
contentService.ApplyWebConfigModifications();
}
private void AddForSharePoint2010()
{
// SP2010 requires IIS7.0
const string valueTemplate = "<add name=\"DownloadHandler for {0}\" path=\"{1}\" verb=\"*\" type=\"MyNamespace.DownloadHandler, MyProject, Version=4.13.0.0, Culture=neutral, PublicKeyToken=******\"/>";
const string xpathTemplate = "add[@name=\"DownloadHandler for {0}\"][@path=\"{1}\"][@verb=\"*\"][@type=\"MyNamespace.DownloadHandler, MyProject, Version=4.13.0.0, Culture=neutral, PublicKeyToken=******\"]";
SPWebService contentService = SPWebService.ContentService;
foreach (var extension in SupportedExtensions)
{
// the Name must be XPATH of Value.. otherwise SP wont remove!
SPWebConfigModification item = new SPWebConfigModification()
{
Owner = FeatureId,
Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode,
Path = "/configuration/system.webServer/handlers",
Name = string.Format(xpathTemplate,extension.Replace("*.", string.Empty), extension),
Value = string.Format(valueTemplate, extension.Replace("*.", string.Empty), extension)
};
contentService.WebConfigModifications.Add(item);
}
contentService.Update();
contentService.ApplyWebConfigModifications();
}
As it can be seen from SupportedExtensions
list, the HTTPHandler is called for those file extensions. Yet this time, I need it to intercept all file downloads from document libraries in Sharepoint. I could simply define SupportedExtensions
as "*", but then the handler will be called for each HTTP request on Sharepoint including css, js, image, html request; which will lead to huge performance problems. That is obviously not acceptable.
So my question is: Is it possible to register and implement an HTTPHandler for only file requests from Document Libraries? Or writing a very efficient handler where it can distinguish a file request from Sharepoint's own files?