customAuthorizedAttribute:authorizeAttribute
{
override public void OnAuthorization (AuthorizationContext filterContext)
{
进行逻辑判断
}
}
给需要进行验证的controller 或者action添加属性标签[customAuthorized]
2 使用BaseController:Controller
protected override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
protected override void HandleUnknownAction(string actionName)
{
base.HandleUnknownAction(actionName);
}
*******************************************************************************
如,断定用户是否登岸,断定用户session是否为空,一般会这个写在页面中:
非论是多情的诗名、摩登的文章,还是闲暇的欢欣,什么都不克不及庖代无比密切的友情。if(HttpContext.Session.IsNewSession)
{
// go to Logon
}
每个须要验证的页面都要如许去写同样的代码,如许的法度是我们不供给的,因为它反复了本身。
当.net呈现Attribute之后,MVC呈现了之后,改变了这一切,若是断定这个页面的接见理否须要登岸或者其它权限,只须要写类似如许的代码即可:
[UserAuthentication(UserToUrlEnum = UserToUrlEnum.Login)]
public ActionResult RegisterRedirect()
{
// code
}
而一般来说,我们的UserAuthentication这个类,我们下文称为过滤器,一般是如许来定义的:
namespace _20110711MVC3的进修.Filter
{
/// <summary>
/// 验证类型列举
/// </summary>
public enum UserToUrlEnum
{
/// <summary>
/// 登录
/// </summary>
Login,
/// <summary>
/// 注册
/// </summary>
Register,
/// <summary>
/// 认证
/// </summary>
Certificate,
}
&#160;
/// <summary>
/// 用户验证过滤器
/// </summary>
public class UserAuthentication : AuthorizeAttribute
{
const string DOMAIN = "http://www.test.com";
public UserToUrlEnum UserToUrlEnum { get; set; }
/// <summary>
/// 机关函数
/// </summary>
public UserAuthentication()
{
this.UserToUrlEnum = UserToUrlEnum.Login;
}
/// <summary>
/// 履行前验证
/// </summary>
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Session.IsNewSession && !ClientHelper.Current.HasUser)
{
switch (this.UserToUrlEnum)
{
case UserToUrlEnum.Login:
{
VCommons.Http.CookieHelper.Write("return_page",
HttpContext.Current.Request.Url.ToString());
HttpContext.Current.Response.Redirect(DOMAIN +
"/Register/Login", true);
}
break;
case UserToUrlEnum.Register:
{
filterContext.HttpContext.Response.Redirect(DOMAIN +
"/Register/Register", true);
}
break;
}
}
else if (this.UserToUrlEnum == UserToUrlEnum.Certificate)
{
filterContext.HttpContext.Response.Redirect(DOMAIN + "/Register/Certificate");
}
&#160;
}
&#160;
}
}
小常识:attribute可以加在类的上方,也可以加在办法的上方,按照实际景象而定。