NClay框架WEB MVC Action Filter设计
处理结构:
Filter1
Filter2
…
Action()
End
End
End
相关实现类代码:
public enum FilterLevel : int
{
High = 0x4000,
Default = 0x2000,
Low = 0x1000
}
[AttributeUsage(AttributeTargets.Class,AllowMultiple= true)]
public class FilterAttribute:Attribute
{
public FilterAttribute(string regexurl)
{
Level = FilterLevel.Low;
RegexURL = regexurl;
}
public FilterLevel Level
{
get;
set;
}
public string RegexURL
{
get;
set;
}
private byte mSequence = 0;
public byte Sequence
{
get
{
return mSequence;
}
set
{
mSequence = value;
}
}
}
public interface IFilterHandler
{
void Execute(FilterContext context);
}
public class FilterContext
{
public FilterContext(IFormContext context)
{
mFormContext = context;
}
private IFormContext mFormContext;
public IFormContext FormContext
{
get
{
return mFormContext;
}
}
public void Execute()
{
Action<FilterContext> action = Handlers.Dequeue();
if (action != null)
action(this);
}
private Queue<Action<FilterContext>> mHandlers = new Queue<Action<FilterContext>>();
internal Queue<Action<FilterContext>> Handlers
{
get
{
return mHandlers;
}
}
}
以上是整个结构的代码,虽然内部整合工厂代码没有提供;但一个简单的FilterContext类已经体现Filter嵌套处理的结构。
简单用例描述:
所有页登录验证Filter
[NClay.Web.Filter("~/.",Level =NClay.Web.FilterLevel.High)]
public class LoginFilter:NClay.Web.IFilterHandler
{
#region IFilterHandler 成员
public void Execute(NClay.Web.FilterContext context)
{
if (context.FormContext.Request.RawUrl.IndexOf("login.aspx",StringComparison.OrdinalIgnoreCase) > 0
|| context.FormContext.Session["_Loginid"] != null)
context.Execute();
else
{
context.FormContext.Response.Redirect("login.aspx");
}
}
#endregion
}
管理验证Filter
[NClay.Web.Filter("~/Admin/.+")]
public class AdminFilter : NClay.Web.IFilterHandler
{
#region IFilterHandler 成员
public void Execute(NClay.Web.FilterContext context)
{
if (context.FormContext.Session["_Loginid"].ToString() == "admin")
context.Execute();
else
context.FormContext.Response.Redirect("/login.aspx");
}
#endregion
}