ASP.NET 3.5自定义配置部分不工作

问题描述:

我正在尝试使用自定义配置节,这是我成功完成了无数次的事情,但由于某种原因,今天它无法正常工作。在配置部分中的代码是:ASP.NET 3.5自定义配置部分不工作

public class RedirectorConfiguration : ConfigurationSection 
{ 
    [ConfigurationProperty("requestRegex", DefaultValue = ".*")] 
    public string RequestRegex { get; set; } 

    [ConfigurationProperty("redirectToUrl", IsRequired = true)] 
    public string RedirectToUrl { get; set; } 

    [ConfigurationProperty("enabled", DefaultValue = true)] 
    public bool Enabled { get; set; } 
} 

从web.config中的相关章节是:

<?xml version="1.0"?> 
<configuration> 
    <configSections> 
     <section name="httpRedirector" type="Company.HttpRedirector.RedirectorConfiguration, Company.HttpRedirector"/> 
    </configSections> 
    <httpRedirector redirectToUrl="http://www.google.com" /> 
</configuration> 

而且我尝试使用的代码在以下的HttpModule:

using System; 
using System.Configuration; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Text.RegularExpressions; 
using System.Web; 

namespace Company.HttpRedirector 
{ 
    public class HttpRedirectorModule : IHttpModule 
    { 
     static RegexOptions regexOptions = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace; 
     static Regex requestRegex = null; 

     public void Dispose() { } 

     public void Init(HttpApplication context) 
     { 
      context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute); 
     } 

     void context_PreRequestHandlerExecute(object sender, EventArgs e) 
     { 
      var app = sender as HttpApplication; 
      var config = ConfigurationManager.GetSection("httpRedirector") as RedirectorConfiguration; 

      if (app == null || app.Context == null || config == null) 
       return; // nothing to do 

      if (requestRegex == null) 
      { 
       requestRegex = new Regex(config.RequestRegex, 
        regexOptions | RegexOptions.Compiled); 
      } 

      var url = app.Request.Url.AbsoluteUri; 
      if (requestRegex != null || requestRegex.IsMatch(url)) 
      { 
       if (!string.IsNullOrEmpty(config.RedirectToUrl)) 
        app.Response.Redirect(config.RedirectToUrl); 
      } 
     } 
    } 
} 

发生了什么事情是配置对象成功回来,但所有标记为“ConfigurationProperty”的属性都设置为null/type默认值,就好像它从未试图映射值配置文件。在启动过程中没有例外。

任何想法这里发生了什么?

+0

NEvermind。我是个白痴。我应该从属性返回base [“propertyName”]。卫生署! – Chris 2009-02-02 18:38:49

您的配置类没有正确的属性。它应该是:

[ConfigurationProperty("requestRegex", DefaultValue = ".*")] 
    public string RequestRegex 
    { 
     get 
     { 
      return (string)this["requestRegex"]; 
     } 
     set 
     { 
      this["requestRegex"] = value; 
     } 
    }