以前判断用户是否登录,判断用户Session是否为空,一般会在这个页面写使用:
if (HttpContext.Session.IsNewSession)
{
//todo Login
}
每个需要验证的页面这样验证,之后.net出现Attribute之后,如果判断某个页面的访问是否登录或者其他权限,只需要:
[UserAuthentication(UserToUrlEnum = UserToUrlEnum.Login)]
public ActionResult RegisterRedirect()
{
// code
}
public enum UserToUrlEnum
{
/// <summary>
/// 登录
/// </summary>
Login,
/// <summary>
/// 注册
/// </summary>
Register,
/// <summary>
/// 认证
/// </summary>
Certificate,
}
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");
}
}
}