仅将页面视图限制为管理员帐户?

时间:2015-04-08 08:11:30

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor

我为一家虚构的私人飞机租赁公司创建了一个小项目。这是我的相关项目文件: https://gist.github.com/anonymous/74d72f7b4c3c37257d16

在这个项目中,我有一个名为App_data的数据库(在我的MyMainDB.mdf解决方案文件夹下)。双击时,它会将我发送到服务器资源管理器,其中包含另一个名为MyMainDBEntities的文件,其中包含我的表格等(其中保存了SystemUsers表)。

我的注册/登录功能已完全实现并正常工作。我还可以在运行解决方案时显示整个用户列表并从网站远程编辑该列表,但是,如何将AdminIndex视图的访问权限仅限于已登录并以{身份登录的用户{1}}?

目前,一旦解决方案正在运行,用户只需导航到以下网址:admin@admin.com,没有任何限制。如果您未以管理员身份登录,我需要在代码方面添加什么才能限制对该网页的访问?有人能告诉我一个如何做到这一点的例子吗?一旦我知道如何做到这一点,我就可以将这些知识应用到我项目的其他关键方面

1 个答案:

答案 0 :(得分:0)

假设MyTemplate是您的控制器,您可以将[authorize]属性添加到您的控制器,如下所示

注意:您可以将其设置为控制器级别或操作级别

[Authorize]
public class MyTemplateController : Controller //Controller level

OR

[Authorize]
public ActionResult AdminIndex() //From the link mentioned above
{
    return View(ss.SystemUsers.ToList());
}

web.config添加此

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

并且您的“登录发布操作”方法使用FormsAuthentication.SetAuthCookie,如下所示:

[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
    // Lets first check if the Model is valid or not
    if (ModelState.IsValid)
    {

            // User found in the database
            if (model.IsValid(model.Email, model.Password )) //According to the design you have in the link given above
            {
                FormsAuthentication.SetAuthCookie(username, false);
                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);
}

那将完成工作。

有关详细信息,请访问 this link