2013年10月26日 星期六

Asp.net MVC 實作登出及驗證(5)

先廢話一下
登入登出看似簡單但有許多需要注意的小地方
參考了很多網站才實作出來
上次做到Asp.net MVC 實作登入驗證(1)
當然要有驗證是否登入跟登出
找了許多站終於結合出比較有效的程式碼
驗證是否已登入,程式碼不長但很實用
if ( User.Identity.IsAuthenticated)
{
  //這邊是有驗證過已登入
}
如果是一整個Controller都需要驗證可加[Authorize]在Class上
如果整個Controller裡有不需驗證的可加[AllowAnonymous]
    [Authorize]
    public class HomeController : Controller
    {       
        [AllowAnonymous]
        public ActionResult Index()
        {
            ViewBag.Title = PublicFunction.WebSiteName; 
            return View();
        }

        public ActionResult Create()
        {
            return View();
        }
     
    }
以下是登出的完整程式碼
 [HttpPost]
        [ValidateAntiForgeryToken]     
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();

            // clear authentication cookie
            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            cookie1.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie1);

            // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
            HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);

            //FormsAuthentication.RedirectToLoginPage(); 
            return RedirectToAction("Index", "Home", null);
        }

參考網站
登出實作
Session.RemoveAll() 及Session.Abandon() 的差別