验证ASP.NET MVC的登录表单

时间:2023-01-17 04:14:31

so I am trying to make my login form to work. I have one table on my database that I want to be able to log in with. The table has two rows, username and password, and when user types in correctly, it should be redirected to the correct page. But when I press the button, nothing happens, what am I doing wrong here?

所以我想让我的登录表单工作。我的数据库上有一个表,我希望能够登录。该表有两行,用户名和密码,当用户输入正确时,应将其重定向到正确的页面。但是当我按下按钮时,没有任何反应,我在这里做错了什么?

Model:

模型:

namespace Barndomshem.Models
{
    public class User
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
}

View:

视图:

<div class="container">
    <div class="row">
        <div class="box">
            <div class="col-lg-12">
                <form class="form-wrapper" id="contact-form" method="post" role="form" novalidate>
                    <div class="form-group">
                        <div class="row">
                            <div class="form-group col-lg-4">
                                <label for="name">
                                    Användarnamn
                                </label>
                                <input type="text" id="name" name="name" class="form-control" data-errmsg="Fyll i användarnamn."
                                       placeholder="Ditt Användarnamn" required />
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="row">
                            <div class="form-group col-lg-4">
                                <label for="number">
                                    Lösenord
                                </label>
                                <input type="text" id="number" name="number" class="form-control" data-errmsg="Fyll i lösenord."
                                       placeholder="Ditt Lösenord" />
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-2 col-sm-2 offset2">
                            <input type="submit" value="Skicka" class="btn btn-primary" />
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

Controller:

控制器:

using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using Barndomshem.Models;


namespace Barndomshem.Controllers
{
    public class RapportController : Controller
    {
        SqlConnection connection = new SqlConnection(@"Data Source=.\SQLExpress;Initial Catalog=Barndomshem;Integrated Security=True");
        SqlCommand command = new SqlCommand();
        SqlDataReader reader;

        public ActionResult Index()
        {
            var user = new User();

            Session["UserName"] = user;

            if (Session["UserName"] == null)
            {
                return RedirectToAction("/Rapport/Validate");
            }

            return View();
        }

        public ActionResult Validate(User user)
        {
            var query = command.CommandText = "SELECT Username FROM User";
            command.CommandType = CommandType.Text;
            command.Connection = connection;

            connection.Open();

            if (user.Username == query)
            {
                return RedirectToAction("/Rapport", user);
            }

            connection.Close();

            return View();
        }
    }
}

1 个解决方案

#1


4  

You're on the right track but there are a couple of problems with your code, namely:

您的问题正确,但您的代码存在一些问题,即:

  • The View is not calling the Validate() action in the controller.
  • View不会在控制器中调用Validate()操作。
  • Your ADO.NET logic to connect to the database is completely wrong.
  • 您的ADO.NET逻辑连接到数据库是完全错误的。
  • Your SQL query does not contain a WHERE clause.
  • 您的SQL查询不包含WHERE子句。
  • You're not making use of [AllowAnonymous] and [Authorize] authentication attributes provided by MVC.
  • 您没有使用MVC提供的[AllowAnonymous]和[Authorize]身份验证属性。

You need to make the following changes to your code:

您需要对代码进行以下更改:

1.Web.config:

1.Web.config:

1.1Add a <connectionStrings> element in the Web.config (under <configuration>):

1.1在Web.config中添加 元素(在 下):

  <connectionStrings>
    <add name="ConnectionString" connectionString="Your connection string"/>
  </connectionStrings> 

1.2Add an <authentication> element in the Web.Config(under <system.web>):

1.2在Web.Config中添加 元素(在 下):

<authentication mode="Forms">
  <forms loginUrl="~/Login/Index" timeout="2880" />
</authentication>

2.Decorate your HomeController with [Authorize]

2.使用[授权]装饰你的HomeController

[Authorize]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

3.LoginController:

3.LoginController:

public class LoginController : Controller
{
    [AllowAnonymous]
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Validate(User user)
    {
        try
        {
            string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            using (var connection = new SqlConnection(cs))
            {
                string commandText = "SELECT Username FROM [User] WHERE Username=@Username AND Password = @Password";
                using (var command = new SqlCommand(commandText, connection))
                {
                    command.Parameters.AddWithValue("@Username", user.Username);
                    command.Parameters.AddWithValue("@Password", user.Password);
                    connection.Open();

                    string userName = (string)command.ExecuteScalar();

                    if(!String.IsNullOrEmpty(userName))
                    {
                        System.Web.Security.FormsAuthentication.SetAuthCookie(user.Username, false);
                        return RedirectToAction("Index", "Home");
                    }

                    TempData["Message"] = "Login failed.User name or password supplied doesn't exist.";

                    connection.Close();
                }
            }
        }
        catch(Exception ex)
        {
            TempData["Message"] = "Login failed.Error - " + ex.Message;
        }
        return RedirectToAction("Index");
    }
}

4.Login Index View:

4.登录索引视图:

@model Barndomshem.Models.User

@using (Html.BeginForm("Validate", "Login"))
{
    <span>User Name</span> <input required="required" type="text" name="Username" /> <br />
    <span>Password</span> <input required="required" type="password" name="Password" />    <br />
    <input type="submit" value="Login" />
}

@if (TempData["Message"] != null)
{
    <span style="color:red;">@TempData["Message"].ToString()</span>
}

Also read the following article:

另请阅读以下文章:

MVC forms authentication by Jon Galloway

MVC由Jon Galloway形成认证

#1


4  

You're on the right track but there are a couple of problems with your code, namely:

您的问题正确,但您的代码存在一些问题,即:

  • The View is not calling the Validate() action in the controller.
  • View不会在控制器中调用Validate()操作。
  • Your ADO.NET logic to connect to the database is completely wrong.
  • 您的ADO.NET逻辑连接到数据库是完全错误的。
  • Your SQL query does not contain a WHERE clause.
  • 您的SQL查询不包含WHERE子句。
  • You're not making use of [AllowAnonymous] and [Authorize] authentication attributes provided by MVC.
  • 您没有使用MVC提供的[AllowAnonymous]和[Authorize]身份验证属性。

You need to make the following changes to your code:

您需要对代码进行以下更改:

1.Web.config:

1.Web.config:

1.1Add a <connectionStrings> element in the Web.config (under <configuration>):

1.1在Web.config中添加 元素(在 下):

  <connectionStrings>
    <add name="ConnectionString" connectionString="Your connection string"/>
  </connectionStrings> 

1.2Add an <authentication> element in the Web.Config(under <system.web>):

1.2在Web.Config中添加 元素(在 下):

<authentication mode="Forms">
  <forms loginUrl="~/Login/Index" timeout="2880" />
</authentication>

2.Decorate your HomeController with [Authorize]

2.使用[授权]装饰你的HomeController

[Authorize]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

3.LoginController:

3.LoginController:

public class LoginController : Controller
{
    [AllowAnonymous]
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Validate(User user)
    {
        try
        {
            string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            using (var connection = new SqlConnection(cs))
            {
                string commandText = "SELECT Username FROM [User] WHERE Username=@Username AND Password = @Password";
                using (var command = new SqlCommand(commandText, connection))
                {
                    command.Parameters.AddWithValue("@Username", user.Username);
                    command.Parameters.AddWithValue("@Password", user.Password);
                    connection.Open();

                    string userName = (string)command.ExecuteScalar();

                    if(!String.IsNullOrEmpty(userName))
                    {
                        System.Web.Security.FormsAuthentication.SetAuthCookie(user.Username, false);
                        return RedirectToAction("Index", "Home");
                    }

                    TempData["Message"] = "Login failed.User name or password supplied doesn't exist.";

                    connection.Close();
                }
            }
        }
        catch(Exception ex)
        {
            TempData["Message"] = "Login failed.Error - " + ex.Message;
        }
        return RedirectToAction("Index");
    }
}

4.Login Index View:

4.登录索引视图:

@model Barndomshem.Models.User

@using (Html.BeginForm("Validate", "Login"))
{
    <span>User Name</span> <input required="required" type="text" name="Username" /> <br />
    <span>Password</span> <input required="required" type="password" name="Password" />    <br />
    <input type="submit" value="Login" />
}

@if (TempData["Message"] != null)
{
    <span style="color:red;">@TempData["Message"].ToString()</span>
}

Also read the following article:

另请阅读以下文章:

MVC forms authentication by Jon Galloway

MVC由Jon Galloway形成认证