How to Modify web.config automatically when using Custom Server Control?
I am trying to create a Custom Server Control in C# us开发者_如何学Going VS2008. I am using this custom control that actually requires me to modify the web.config
file in order to add an HttpHandler
when this control is added to the page of client.
My question is fairly simple:
What needs to be added to my custom control code so it registers the required HttpHandler
information in the web.config
? Some native controls already do this. For example, the AJAX Toolkit
will modify the web.config. How can I do something similar with my control?
If you have an item in the toolbox of Visual Studio you can perform such an action when the developer drags and drops the control onto the web page. You need to decorate your control with System.ComponentModel.DesignerAttribute
to refer it to a subclass (which you create) of System.Web.UI.Design.ControlDesigner
. In this class you can override Initialize
and in there you can get hold of the config via System.Web.UI.Design.IWebApplication
something like this:
var service = this.GetService(typeof(System.Web.UI.Design.IWebApplication)) as IWebApplication;
if (service != null)
{
var configuration = service.OpenWebConfiguration(false);
if (configuration != null)
{
var section = configuration.GetSection("system.web/httpHandlers") as HttpHandlersSection;
if (section != null)
{
var httpHandlerAction = new HttpHandlerAction("MyAwesomeHandler.axd", typeof(MyAwesomeHandler).AssemblyQualifiedName, "GET,HEAD", false);
section.Handlers.Add(httpHandlerAction);
configuration.Save();
}
else
{
// no system.web/httpHandlers section found... deal with it
}
}
else
{
// no web config found...
}
}
else
{
// Couldn't get IWebApplication service
}
Review the Any way to add HttpHandler programmatically in .NET? thread, which descries how to accomplish a similar task at runtime. Hope this helps.
精彩评论