簡體   English   中英

使用c#在mvc4中進行表單身份驗證

[英]Form Authentication in mvc4 using c#

嗨,我正在使用c#在mvc4中進行我的web項目。 現在我正在創建一個登錄頁面。 我使用的下面的代碼。用戶名和密碼在sql數據庫表中

視圖

@using (Html.BeginForm())
{
    @Html.LabelFor(model => model.Mem_Email)

    @Html.EditorFor(model => model.Mem_Email)
    @Html.ValidationMessageFor(model => model.Mem_Email)

    @Html.LabelFor(model => model.Mem_PWD)

    @Html.EditorFor(model => model.Mem_PWD)
    @Html.ValidationMessageFor(model => model.Mem_PWD)

    <input type="submit" value="Log In" />
}

調節器

public ViewResult Login()
{
    return View();
}

[HttpPost]
public RedirectResult Login(FormCollection form)
{
    string uid = Request.Form["Log_email"];
    string pwd = Request.Form["Log_pwd"];
    bool IsUser=new Member().GetLogin(uid,pwd);
    if (IsUser == true)
    {
        System.Web.Security.FormsAuthentication.SetAuthCookie(uid, true);
        return Redirect("~/Member/MemberHome");
    }
    else 
        return Redirect("~/Member/Login");
}

模型

 public bool GetLogin(string email,string pwd)
 {
     bool IsUser = false;
     using (SqlConnection con = new SqlConnection(Config.ConnectionString))
     {
         using (SqlCommand cmd = new SqlCommand(
             "SELECT COUNT (*) FROM Mem_Register WHERE Mem_Email='" + 
             email + "' AND Mem_PWD='" + pwd + "'", con))
         {
             con.Open();
             int count = (int)cmd.ExecuteScalar();
             if (count == 1)
             {   IsUser = true;   }
         }
     }
     return IsUser;      
 }

這不起作用。表單中的內容不會傳遞給控制器​​。 我不知道這是登錄用戶的正確方法。 請幫我。

首先,您不應該使用FormCollection。 由於您使用的是強類型模型,因此您應該將該模型發布到您的操作中。

其次,您在視圖中使用名稱Mem_EmailMem_PWD ,但您正在尋找Log_emailLog_pwd FormCollection值,這是您找不到的。

在View中使用此代碼

@using (Html.BeginForm())
{
  <div>
    <fieldset>
        <legend>Login</legend>

            @Html.LabelFor(u => u.Email)

           @Html.TextBoxFor(u => u.Email)
            @Html.ValidationMessageFor(u => u.UserName)

            @Html.LabelFor(u => u.Password)

            @Html.PasswordFor(u => u.Password)
            @Html.ValidationMessageFor(u => u.Password)


        <input type="submit" value="Log In" />
    </fieldset>
  </div>
}

@Erik給出的解決方案是正確的,您在控制器中使用不同的命名約定。 您必須使用視圖中相同的Form值

[HttpPost]
public RedirectResult Login(FormCollection form)
{
string uid = Request.Form["Mem_Email"];
string pwd = Request.Form["Mem_Email"];
bool IsUser=new Member().GetLogin(uid,pwd);
if (IsUser == true)
{
    System.Web.Security.FormsAuthentication.SetAuthCookie(uid, true);
    return Redirect("~/Member/MemberHome");
}
else 
    return Redirect("~/Member/Login");
}

使用較早的一個,即Log_emailLog_pwd您將在控制器中獲得空值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM