MVC中的自定义身份验证
问题描述:
我有一个自定义身份验证设置,以便用户存储为会话变量。一旦他们去通过账户/登录过程中,我在会话中存储从第三方API返回用户的细节是这样的:MVC中的自定义身份验证
Session["User"] = new UserViewModel(result);
我要检查用户出现之前,每个控制器动作,所以我有做在它下面的检查一个BaseController:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (Session["User"] != null)
base.OnActionExecuting(filterContext);
else
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { action = "LogIn", controller = "Account" }));
每个控制器然后从BaseController继承,以便它重定向到登录页面,如果没有用户。我不从AccountController的BaseController继承,这样它就不会进入无限循环的检查和重定向,但我也想让特定的页面不检查登录。有没有办法做到这一点,即以与[AllowAnonymous]相同的方式编写例外规则?
答
你可以在这些方法为使用过滤器:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class ActionCheckAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower().Trim();
string actionName = filterContext.ActionDescriptor.ActionName.ToLower().Trim();
// this is just a sample.. you can implement any logic you want
if (!actionName.StartsWith("your method name") && !controllerName.StartsWith("your controller name"))
{
var session1 = HttpContext.Current.User.Identity.Name;
HttpContext ctx = HttpContext.Current;
//Redirects user to login screen if session has timed out
if (session1 == null)
{
base.OnActionExecuting(filterContext);
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Account",
action = "LogOff"
}));
}
}
}
}
然后控制器把属性为:
[ActionCheck]
public class MyController : Controller
{
public ActionResult Index()
{
return View();
}
}
,或对具体的操作方法为:
[ActionCheck]
public Actionresult SomeMethod()
{
return View();
}
为什么不创建一个自定义的授权属性,并将其仅应用于要执行此检查的控制器? – Alex
覆盖授权属性而不是ActionFilters –