Authorize属性如何在MVC3中工作

时间:2013-05-21 08:40:41

标签: asp.net-mvc-3

我研究了mvc3,我在asp.net网站上阅读了很多文章或观看视频。 在我对mvc3有一些了解后,我对授权属性的问题进行了验证用户登录与否。 当我创建一个页面来验证用户时的默认代码:

[HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (Membership.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

如果我不想使用Membership和FormsAuthentication(不要说关于Windows身份验证)来授权用户。那么有什么方法可以创建一些东西来验证用户以及当我使用授权时  属性它将像我使用成员身份和FormsAuthentication 时那样工作。我不知道Authorize属性用于验证用户登录与否,我可以自己创建会话或cookie来验证用户身份。如果我的问题不清楚,请告诉我! 谢谢你的阅读!

1 个答案:

答案 0 :(得分:3)

您可以做的就是滚动自己的授权属性,如下所示:

public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{

    protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
    {
        //Put your authorisation check here
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        //put your redirect to login controller here
    }
}