如何在MVC 4中使用自定义帐户制作受保护的页面

时间:2014-04-30 07:58:09

标签: asp.net-mvc asp.net-mvc-4

我正在使用看起来像的Custome用户帐户 型号:USer

public class user
    {
        [Key]
        public int userid { get; set; }


        [Required]

        [StringLength(150)]
        [DisplayName("Email")]
        public string Email { get; set; }
        [DisplayName("Password")]
        [Required]
        [DataType(DataType.Password)]
        [StringLength(20, MinimumLength = 6)]
        public string Password { get; set; }
        public string PasswordSalt { get; set; }
    }

控制器:

public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult logIn()
        {
            return View();
        }

        [HttpPost]
         public ActionResult logIn(Models.user user)
        {
            if (ModelState.IsValid)
            {
                if (user !=null)
                {
                    FormsAuthentication.SetAuthCookie(user.Email, false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "Login Data is Incorrect.");
                }
            }
            return View(user);
        }


        [HttpGet]
        public ActionResult Registration()
        {
            return View();
        }


        [HttpPost]
        public ActionResult Registration(Models.user user)
        {
            if (ModelState.IsValid)
            {

                var sysUser = db.users.Create();

                sysUser.Email = user.Email;
                sysUser.Password = user.Password;


                db.users.Add(sysUser);
                db.SaveChanges();
                return RedirectToAction("Index", "Home");

            }

        else
    {
        ModelState.AddModelError("","Login Data is Incorrect.");

    }
               return View();

    }
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index","home");
        }

Login.CSHTML(查看)

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true, "Login Failed. Check your Details.");
   <div>
   <fieldset>
   <legend>Login Form</legend>
   <div>@Html.LabelFor(u=>u.Email)</div>

   <div>@Html.TextBoxFor(u=> u.Email)
   @Html.ValidationMessageFor(u=>u.Email)
   </div>

   <div>@Html.LabelFor(u=>u.Password)</div>

   <div>@Html.PasswordFor(u=> u.Password)
   @Html.ValidationMessageFor(u=>u.Password)
   </div>

   <input type ="submit" Value="Login" />
   </fieldset>
   </div> 
   }

这是有效的代码:  我想建立一个管理员和一些用户...我想为用户保护一些页面......

2 个答案:

答案 0 :(得分:0)

您可以通过继承AuthorizeAttribute类来实现 CustomAuthentication 来实现此功能。这将限制对操作方法或整个控制器的访问。您需要覆盖两种主要方法 - AuthorizeCore() HandleUnauthorizedRequest()

对于exa。在这里我定义了一个类,比如说CustomAuthentication,它检查用户是否有权访问。

public class CustomAuthentication : AuthorizeAttribute
    {
        private bool isAuthorized { get; set; }

        /// <summary>
        /// This function will return true if user authenticated user else return false
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            try
            {
                isAuthorized = true;

                if (!CheckUserLogin()) // This function check the user rights 
                {
                    isAuthorized = false;
                }

                return isAuthorized;

            }
            catch (Exception)
            {
                isAuthorized = false;
                return isAuthorized;
            }
        }

    /// <summary>
    /// If user is not authorize user then redirect it to Login page
    /// </summary>
    /// <param name="filterContext"></param>
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        try
        {
            string controllerName = filterContext.RouteData.GetRequiredString("controller").ToLower();
            string actionName = filterContext.RouteData.GetRequiredString("action").ToLower();


            if (!isAuthorized)
            {
                // if the request is AJAX return JSON else view.
                if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
                {
                    filterContext.Result = new JavaScriptResult { Script = "redirectToLogin()" };
                }
                else
                {
                    RouteValueDictionary objCollect = filterContext.RouteData.Values;
                    string strRedirect = string.Empty;

                    // This logic is to construct the returnURL, you can ignore this part
                    for (int i = 2; i < objCollect.Count; i++)
                    {
                        strRedirect += objCollect.Keys.ElementAt(i) + "=" + Convert.ToString(objCollect.Values.ElementAt(i)) + "&"; 
                    }

                    var objQrystr = filterContext.HttpContext.Request.QueryString;
                    // Get the query-string and append it to URL
                    for (int i = 0; i < objQrystr.Count; i++)
                    {
                        strRedirect += objQrystr.GetKey(i) + "=" + Convert.ToString(objQrystr[i]) + "&"; 
                    }

                    if (!string.IsNullOrEmpty(strRedirect))
                    {
                        strRedirect = "?" + strRedirect.TrimEnd('&');
                    }
                   // End of Logic of constructing the returnURL

                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login", action = "LogOn", returnUrl = "/" + controllerName + "/" + actionName + strRedirect}));
                }
            }

        }
        catch (Exception)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login", action = "LogOn" }));
            return;
        }

    }

现在,您必须使用此自定义属性修饰控制器或操作。像这样 -

[CustomAuthenticate()]
public class MyShopingController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

除上述示例外,您还可以从this blog获取引用。

答案 1 :(得分:0)

创建自定义操作过滤器以处理您的授权要求。请查看以下链接

http://www.asp.net/mvc/tutorials/hands-on-labs/aspnet-mvc-4-custom-action-filters http://www.codeproject.com/Articles/650240/A-Simple-Action-Filter-Overview

希望这有帮助, DSR