demoshop

demo, trying to be the best_

ASP.NET MVC Form 驗證

  • 2009-02-11
  • 30836
  • 0
官方網站
http://www.asp.net/mvc

一個網頁很難不需要驗證使用者是否登入的機制,在ASP.NET MVC中有很方便的機制可以直接使用,但是有時候我們並不需要搞到那麼複雜的驗證,只是要做一個簡單的驗證,demo今天在做活動頁面的時候剛好有個統計資料不想讓每個人都可以看到所以實做了一個簡單的驗證機制。

根據ASP.NET MVC Tutorials第17單元Authenticating Users with Forms Authentication的說明可以利用附加Attribute的方式來達到Action的驗證,只需要一個[Authorize]就可以了,甚至可以直接丟到Class級對所有的Action的驗證,所以說後端驗證機制相當簡單,因此好像沒有道理不用它的機制來跑,但是demo需要的是極為簡單的驗證就好了,沒興趣去搞一個ASPMemberShip資料庫出來,所以我就這樣做啦。

我們將範例的HomeController的About()加上驗證

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

(不要懷疑真的就是這樣而已)


然後我們可以直接使用範本建立好的LogOn.aspx把它的form改一下,用我們自己的Controller

<% using (Html.BeginForm("login","Login")) { %> 

直接來建立一個LoginController,內容我就直接貼了註解在裡面吧

public class LoginController : Controller
{
 
    public ActionResult Login()
    {
        return View();
    }
 
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Login(string userName, string password, bool rememberMe, string returnUrl)
    {
        if (ValidateLogOn(userName, password))
        {
            string strUsername = userName.ToLower();
            if (strUsername == "admin" && password == "1234")
            {
                //下面這段是.NET原本就有的所以我們利用這段就可以符合寫法
                System.Web.Security.FormsAuthentication.RedirectFromLoginPage(strUsername, true);
                //驗證成功後導向首頁
                return RedirectToAction("Index", "Home");
            }
            //驗證失敗導向about頁
           return RedirectToAction("about", "Home");
        }
        //如果帳號或密碼沒輸入就回到原頁
        return View();
    }
 
    //以下這是範例中的基本驗證,demo直接Copy過來
    private bool ValidateLogOn(string userName, string password)
    {
        if (String.IsNullOrEmpty(userName))
        {
            ModelState.AddModelError("username", "You must specify a username.");
        }
        if (String.IsNullOrEmpty(password))
        {
            ModelState.AddModelError("password", "You must specify a password.");
        }
        return ModelState.IsValid;
    }
 
} 

直接來執行會發生錯誤,這是因為web.config設定的問題,我們把它改一下讓沒有登入時直接會導向登入頁

<authentication mode="Forms">
  <forms loginUrl="~/Account/Logon" />
</authentication> 

然後你在測試就可以發現你的網站有簡單的密碼驗證了

 

其實這些觀念和用法是基本用法,並不是ASP.NET MVC的東西,除了[Authorize]以外,有很多人寫ASP.NET的時候還是習慣利用Session來驗證,如果是真的有需要那沒話說但是很多人只是因為習慣而沿用下去,不知道.NET已經幫我們做了很多事情,改變才能成長!!

 

http://blog.miniasp.com/post/2008/02/Explain-Forms-Authentication-in-ASPNET-20.aspx

回應討論