中文字幕精品亚洲无线码二区,国产黄a三级三级三级看三级,亚洲七七久久桃花影院,丰满少妇被猛烈进入,国产小视频在线观看网站

雁過請留痕...
代碼改變世界

[mvc] 簡單的forms認證(zheng)

2018-05-07 17:09  xiashengwang  閱讀(282)  評論(0)    收藏  舉報

1、在web.config的system.web節點(dian)增(zeng)加authentication節點(dian),定義如下:

  <system.web>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime targetFramework="4.5.2"/>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880">
        <credentials passwordFormat="Clear">
          <user name="user" password="pwd001"/>
          <user name="admin" password="pwd002"/>
        </credentials>
      </forms>
    </authentication>
  </system.web>

2,新增AccountController。

    public class AccountController : Controller
    {
        // 用于初期表示用
        public ActionResult Login()
        {
            return View();
        }

        // 登錄按鈕
        [HttpPost]
        public ActionResult Login(string username, string password, string returnUrl)
        {
            bool result = FormsAuthentication.Authenticate(username, password);
            if (result)
            {
                FormsAuthentication.SetAuthCookie(username, false);
                return Redirect(returnUrl ?? Url.Action("Index", "Admin"));
            }
            else
            {
                ModelState.AddModelError("", "Incorrect username or password");
                return View();
            }
        }
    }

3、Login.cshtml

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary()
        <p><label>Username:</label><input name="username" type="text" /></p>
        <p><label>Password:</label><input name="password" type="password" /></p>
        <input type="submit" value="Log in"/>
    }
</body>
</html>

4、瀏覽器(qi)輸入(ru)//localhost:44324/Account/Login,輸入(ru)web.config中(zhong)定(ding)義的用戶名和(he)密碼,成功就會進入(ru)Admin/Index頁面。

5、其他頁面如何進行(xing)認證?

1)在(zai)action中加Request.IsAuthenticated判斷

    public class AdminController : Controller
    {
        // GET: Admin
        public string Index()
        {
            if (!Request.IsAuthenticated)
            {
                FormsAuthentication.RedirectToLoginPage();
            }
            return "welcome to Admin page!";
        }
    }

2)在action方法上(shang)加Authorize特(te)性

    public class AdminController : Controller
    {
        // GET: Admin
        [Authorize]
        public string Index()
        {
            return "welcome to Admin page!";
        }
    }

3)在controller上加Authorize特性(xing)(所有的action都會應用(yong)上)

    [Authorize]
    public class AdminController : Controller
    {
        // GET: Admin
        public string Index()
        {
            return "welcome to Admin page!";
        }
    }