|
|
2#

楼主 |
发表于 2008-11-14 17:50:18
|
只看该作者
自定义了两个自定义Attribute,分别为:RequiresAuthenticationAttribute和RequiresRoleAttribute。通过这两个Attribute来可以作用于Class和Method,用标记哪些Controller或Action需要登录后,或者需要拥有哪些角色才能执行。如果用户没有拥有访问当然Controller或Action权限的时候,就会自动被重定向到登录页面去。下面是两个类的定义:
/// <summary>
/// Checks the User's authentication using FormsAuthentication
/// and redirects to the Login Url for the application on fail
/// </summary>
[RequiresAuthentication]
public class RequiresAuthenticationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//redirect if not authenticated
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
//use the current url for the redirect
string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
//send them off to the login page
string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
} |
|