使用c#在mvc4中进行表单身份验证
本文关键字:表单 身份验证 mvc4 使用 | 更新日期: 2023-09-27 18:29:12
hi我正在mvc4中使用c#进行我的web项目。现在我正在创建一个登录页面。我用过以下代码。用户id和密码在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_Email
和Mem_PWD
,但您正在查找Log_email
和Log_pwd
的FormCollection值,但您找不到这些值。
在查看中使用此代码
@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_email
和Log_pwd
,您将在控制器中获得null值。