简体   繁体   English

验证登录表单 ASP.NET MVC

[英]Validate login form ASP.NET MVC

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();
        }
    }
}

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.视图没有调用控制器中的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>元素(在<configuration> ):

  <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(在<system.web> )添加一个<authentication>元素:

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

2.Decorate your HomeController with [Authorize] 2.用[Authorize]装饰你的HomeController

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

3.LoginController: 3.登录控制器:

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 Jon Galloway 的 MVC 表单身份验证

 private void Button_Click(object sender, EventArgs e)
    {
        String user = txtUser.Text;
        String Password = txtPassword.Text;

        if (user == "admin" & Password == "admin123")
        {
            MessageBox.Show("Login Successfully", "info", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        else if( (user == "" || Password == "") || (user == "" && Password == ""))
        {
            MessageBox.Show("Please Enter User Name and Password!", "info", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }          
        
        else
            MessageBox.Show("Incorrect Username or Password", "alter", MessageBoxButtons.OK, MessageBoxIcon.Error);                   
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM