验证ASP.NET MVC的登录表单

时间:2016-08-06 19:19:53

标签: c# asp.net .net asp.net-mvc asp.net-mvc-4

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

型号:

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

查看:

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

控制器:

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

2 个答案:

答案 0 :(得分:4)

您已走上正轨但您的代码存在一些问题,即:

  • 视图未调用控制器中的Validate()操作。
  • 您的ADO.NET逻辑连接到数据库是完全错误的。
  • 您的SQL查询不包含WHERE子句。
  • 您未使用MVC提供的[AllowAnonymous][Authorize]身份验证属性。

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

<强> 1.Web.config:

1.1在Web.config中添加<connectionStrings>元素(在<configuration>下):

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

1.2在Web.Config中添加<authentication>元素(在<system.web>下):

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

2.使用[Authorize]

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

<强> 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.登录索引视图:

@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>
}

另请阅读以下文章:

MVC forms authentication by Jon Galloway

答案 1 :(得分:-1)

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