在mvc3中经常使用身份验证实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PetsStore.Models;
using PetsStore.EntitiesRepositories;
namespace PetsStore.Filters
{
public class AdminAttribute:AuthorizeAttribute
{
private UserRepository userRepository = new UserRepository();
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.User.Identity.IsAuthenticated)
{
return false;
}
var userName=httpContext.User.Identity.Name;
User user = userRepository.GetByUserName(userName);
if (!Roles.Contains(user.Role.RoleName))
{
return false;
}
return true;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectResult(string.Format("/Account/AdminLogin?ReturnUrl={0}/{1}", filterContext.RouteData.Values["controller"], filterContext.RouteData.Values["action"]));
}
else
{
filterContext.Result = new ContentResult() { Content = "对不起,您的权限不足!" };
}
}
}
}