Creating a Custom Condition
Custom conditions allow you to extend the UrlRewriter.NET component with your own conditions.
Follow these steps to create your custom condition:
- Create a class that implements the IRewriteCondition interface. This class will be executed when the condition is required to be evaluated.
/// <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;
} - Create an condition parser class that implements the IRewriteConditionParser interface. This class will be called by UrlRewriter.NET when reading the rewriting rules and it recognises your condition name. Note that your condition parser *must* work even if its required attributes do not exists, as it may be called by UrlRewriter.NET on all nodes.
/// <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;
}
} - Register your custom condition parser.
<register parser="MyNamespace.Parsers.ExistsConditionParser, MyAssembly� />
- Use your custom condition.
<if mycondition="something"> .... </if>