【问题标题】:How Authorize attribute work in MVC3授权属性在 MVC3 中的工作原理
【发布时间】:2014-06-02 10:38:41
【问题描述】:

我研究了 mvc3,我在 asp.net 网站上阅读了很多文章或观看视频。 在我对 mvc3 有所了解之后,我对 Authorize 属性来验证用户是否登录有疑问。 当我创建一个页面来验证用户时的默认代码是这样的:

[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 身份验证)来授权用户。那么有什么方法可以创建一些东西来验证用户以及当我使用 Authorize 当我使用 Membership 和 FormsAuthentication 时,它会像我一样工作。我不知道用于验证用户身份的 Authorize 属性是否是登录,因此我可以自己创建会话或 cookie 来验证用户身份。如果我的问题不清楚,请告诉我! 感谢阅读!

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    你可以做的是像这样滚动你自己的授权属性:

    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
        }
    }
    

    【讨论】:

    • 感谢您尽快回复我。就像你说的我不能做一些非常简单的事情来验证用户?例如,当用户登录时,我将自己创建一个会话或 cookie,当我调用 Authorize 属性时,它会知道用户登录与否。或者我必须使用 Formauthentication 对用户进行身份验证,之后 Authorize 属性可以像 Def​​ault 一样工作。
    猜你喜欢
    • 1970-01-01
    • 2015-12-18
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    相关资源
    最近更新 更多