Mvc如何做权限

需求是这样的,例如我们现在做网站的后台都是需要管理员来登录的.那么如果管理员没有登录就不允许访问这个后台的任何文件.登录后才可以访问.那么在Mvc里面怎么实现呢?

好跟我来

我们先建一个mvc的空项目

在添加一个Account文件夹,并在里面添加3个文件LogOn.aspx、AA.aspx、BB.aspx.

LogOn.aspx文件里就做一个登录的表单,

<% Html.BeginForm("LogOn","Account", FormMethod.Post); %>
<dl>
    <dt>账号:</dt>
    <dd><%= Html.TextBox("name") %></dd>
    <dt>密码:</dt>
    <dd><%= Html.TextBox("pwd") %></dd>
</dl>
<input type="submit" value="登陆" />
<% Html.EndForm(); %>

AA.aspx、BB.aspx随便放些文字什么的.(用来测试用的)

然后增加一个Controller文件夹增加一个AccountController.cs文件

敲入

     

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

      [HttpPost]
      public ActionResult LogOn(FormCollection FormValue)
      {

          //这里可以做一些判断数据的代码,如果成立就执行FormsAuthentication.SetAuthCookie("admin",false);
          FormsAuthentication.SetAuthCookie("admin",false);
          return View()

      }

[Authorize]//这个是验证如果用户还没有登录就不执行这段代码,并返回登录页面
public ActionResult AA()
{
    return View();
}

[Authorize]
public ActionResult BB()
{
    return View();
}

好最好轮到设置配置文件,要设置最外面那个Web.config哦

<system.web>

下面添加

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

loginUrl="~/Account/LogOn" 这个是登录页面

ok大概就这样了

哦还有,如何退出登陆。只要调用FormsAuthentication.SignOut();就可以退出登陆了

原文地址:https://www.cnblogs.com/lvcha/p/1714235.html