在ASP.net MVC中进行身份认证

@using (Html.BeginForm("Login", "Home"))
{ 
    <input type="text" name="adminName" />
    <br />
    <input type="password" name="pwd" />
    <input type="submit" name="name" value="登录" />
}
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

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

        public ActionResult Login()
        {
            string name = HttpContext.Request.Form["adminName"];
            string pwd = HttpContext.Request.Form["pwd"];
            //拿到用户输入的账号密码之后需要去后台数据库进行验证,若验证通过则继续。
            //先将通过验证的用户名存放到session中。
            Session["user"] = name;
            //为当前用户名提供一个身份证票据,并将该票证添加到Cookie。
            System.Web.Security.FormsAuthentication.SetAuthCookie(name, false);
            return Content("123");
        }

        [Authorize]
        public ActionResult DoSth()
        {
            //如果使用了Authorize特性,则不需要使用下面这个判断。
            if (this.User.Identity.IsAuthenticated)//如果存在身份认证标识
            {
                //string adminName = this.User.Identity.Name;//获取写入的adminName。
            }
            return View();
        }

        [Authorize]
        public ActionResult LoginOut()
        {
            System.Web.Security.FormsAuthentication.SignOut();//这里删除凭据之后,需要将页面跳转到登录页面才行,否则this.User.Identity.IsAuthenticated仍然为true
            Session["user"] = null;//清楚session
            return RedirectToAction("Index", "Home");
        }
    }
}

在Web.config文件中进行相关配置。过期时间为30分钟。跳转页面

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    
    <authentication mode="Forms">
      <forms loginUrl="~/Home/Index" timeout="30"></forms>
    </authentication>

猜你喜欢

转载自www.cnblogs.com/vichin/p/12245387.html