开源地址重写

Open Source URL Rewriter for .NET / IIS / ASP.NET
英文官方站:UrlRewriter.NET    中文支持站:UrlRewriter.CN
您的位置:首页参考手册详细参考条件创建自定义条件 → 浏览:创建自定义条件的详细说明

创建自定义条件

自定义条件可以帮助您扩展UrlRewriter.NET 的功能:

下面是创建自定义条件的步骤和方法:

  1. 从IRewriteCondition接口创建一个类,此类将在条件被调用的时候执行:
    /// <summary>
    /// Condition that tests the existence of a file.
    /// </summary>
    internal class ExistsCondition : IRewriteCondition
    {
    /// <summary>
    /// Constructor.
    /// </summary>
    /// <param name="location"></param>
    public ExistsCondition(string location)
    {
    _location = location;
    }

    /// <summary>
    /// Determines if the condition is matched.
    /// </summary>
    /// <param name="context">The rewriting
    context.</param>
    /// <returns>True if the condition is met.</returns>
    public bool IsMatch(RewriteContext context)
    {
    string filename = HttpContext.Current.Server.
    MapPath(context.Expand(_location));
    return File.Exists(filename) ||
    Directory.Exists(filename);
    }

    private string _location;
    }
  2. 从IRewriteConditionParser接口创建一个类,此类是要创建的条件的解析器:
    /// <summary>
    /// Parser for exists conditions.
    /// </summary>
    internal class ExistsConditionParser : IRewriteConditionParser
    {
    /// <summary>
    /// Parses the condition.
    /// </summary>
    /// <param name="node">The node to parse.</param>
    /// <returns>The condition parsed, or null
    if nothing parsed.</returns>
    public IRewriteCondition Parse(XmlNode node)
    {
    XmlNode existsAttr = node.Attributes.
    GetNamedItem("mycondition");
    if (existsAttr != null)
    {
    return new
    ExistsCondition(existsAttr.Value);
    }
    return null;
    }
    }
  3. 注册自定义条件:
    <register parser="MyNamespace.Parsers.ExistsConditionParser,
    MyAssembly" />
  4. 使用自定义条件:
    <if mycondition="something">
    ....
    </if>
参考