【问题标题】:How to Modify web.config automatically when using Custom Server Control?使用自定义服务器控件时如何自动修改 web.config?
【发布时间】:2011-11-30 03:40:15
【问题描述】:

我正在尝试使用 VS2008 在 C# 中创建自定义服务器控件。我正在使用这个自定义控件,实际上需要我修改web.config 文件,以便在将此控件添加到客户端页面时添加HttpHandler

我的问题很简单:

需要在我的自定义控制代码中添加什么以便在web.config 中注册所需的HttpHandler 信息?一些本机控件已经这样做了。例如,AJAX Toolkit 将修改 web.config。我怎样才能用我的控件做类似的事情?

【问题讨论】:

    标签: c# asp.net web-config custom-server-controls


    【解决方案1】:

    查看Any way to add HttpHandler programmatically in .NET? 线程,该线程描述了如何在运行时完成类似的任务。希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      如果您在 Visual Studio 的工具箱中有一个项目,您可以在开发人员将控件拖放到网页上时执行此类操作。您需要使用System.ComponentModel.DesignerAttribute 装饰您的控件,以将其引用到System.Web.UI.Design.ControlDesigner 的子类(您创建的)。在这个类中,您可以覆盖 Initialize 并在那里您可以通过 System.Web.UI.Design.IWebApplication 获取配置,如下所示:

      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
      }
      

      【讨论】:

      • 我在下面写了代码,但它没有工作。如果我做错了什么,请检查 if (service != null) { var configuration = service.OpenWebConfiguration(false); if (configuration != null) { var section = configuration.GetSection("system.web/httpModules") as HttpHandlersSection; HttpModuleAction a = new HttpModuleAction("Tools","CC,Tools") ;section.add(a);
      • 添加该部分后,您需要发送configuration.Save()
      • 我已经添加了部分配置。保存(),但仍然无法正常工作,请帮助我。
      • @KrishnaYadav 我进一步充实了示例,添加了 HttpHandlerAction 代码。您可能需要在 else 块中添加一些代码,以确保您不会结束。
      猜你喜欢
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 2010-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多