Tuesday, June 17, 2008

Programatically add (and remove) an HttpModule to SharePoint Web.config

Sometimes you need to use an HttpHandler or HttpModule in a SharePoint application - I am using one to handle the requests to the system pages and to replace the application.master on them with my own master. To install this module I need to register the dll in the GAC and to add a HttpModule declaration in the web.config.

To modify the web.config programatically in SharePoint you can use the SPWebConfigModification class. There are many examples on the net about using this class, and the one I started with is
this one. Unfortunately, this example, along with all the others on the subject are healing with adding HttpHandler elements, while I needed to play with an HttpModule element. The example does apply to me for adding an element, but the issue arises when I need to remove it.

The SPWebConfigModification class has a Name property. This property should be set to the relative XPath to the modification and maps to the Path attribute of an HttpHandler element. The property is used to locate the element when you need to remove it. Unfortunately, the HttpModule element does not have the Path attribute. So no matter how I tried it, I could not remove the element from the web.config.

The solution came while I was reading a different post about web.config inheritance: the tag. If you want to remove the HttpModule element, add a tag to the web.config.

Posted by Madalina at 11:34:33 | Permanent Link | Comments (2) |
Comments
1 - Can you show an example of this, I need to implement this functionality for a client. (Comment this)

Written by: David Jacobus at 2008/07/30 - 14:24:17
profile
2 - Sure :)

Starting form the sample I mentioned above, here is the code that adds the module to web.config:

string assmDetails = string.Format(CultureInfo.InvariantCulture, "Namespace.Module, Module, Version=1.0.0.0, Culture=neutral, PublicKeyToken=****************");


SPWebConfigModification modification = new SPWebConfigModification( "Module1.0", "configuration/system.web/httpModules");
modification.Owner = "Module1.0";
modification.Sequence = 0;
modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;

SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();

And here is the code that removes it:

SPWebConfigModification modificationR = new SPWebConfigModification( "Module1.0", "configuration/system.web/httpModules/remove");
modification.Value = string.Format(CultureInfo.InvariantCulture, "", assmDetails);
webApp.WebConfigModifications.Add(modification);

Careful though, multiple tags of the same module are not a problem, but multiple <remove> tags are.
 (Comment this)

Written by: Madalina at 2008/07/30 - 14:38:25
Write a comment