我正在尝试使用自定义配置部分,我之前已经成功完成了很多次,但由于某种原因,今天它不起作用。配置部分的代码是:
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”的属性都设置为空/类型默认值,就好像它从未尝试映射配置文件中的值一样。启动过程中没有异常。
知道这里发生了什么吗?