繁体   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