您的位置:首页 > 博客中心 > 前端开发 >

asp.net mvc3登录验证

时间:2022-04-09 11:49

1,在web.config中  <system.web>节点下面增加:

    <authentication mode="Forms">
      <forms name=".IndexCookies" loginUrl="~/Account/LogIn" defaultUrl="~/Home/Index" timeout="60" domain="">
      </forms>
    </authentication>
    <authorization>
      <deny users="?" />
    </authorization>

这里设置了必须登录LogIn页面,然后才会跳转到首页。

timeout为60分钟。

<deny users = "?"/>、 是拒绝匿名用户访问
<allow users= "*" /> 允许所有的用户访问包括匿名用户 

 

2,有一些js文件、css文件,需要允许所有人访问,这样登录页面才显示正常。

和<system.web>同一级,在<system.web>的上面添加下面配置:

  <location path="bootstrap">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
  <location path="Scripts">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>

3,登录和退出代码:

        [HttpPost]
        public string Login(string user, string password)
        {
            string result = userDal.Login(user, password);
            if (result == "登录成功")
            {              
               FormsAuthentication.SetAuthCookie(user, false);
                //Session["username"] = user; 不需要通过Session来保存用户名,User.Identity.Name可以直接取到
            }
            return result;                    
        }

         [HttpPost]
        public void Logout()
        {
            FormsAuthentication.SignOut();
            //Session["username"] = null;            
            
        }

4,获取用户名使用 

User.Identity.Name

 

本类排行

今日推荐

热门手游