2016-08-06 2 views
1

私はログインフォームを動作させようとしています。データベースに、ログインできるテーブルが1つあります。表にはユーザー名とパスワードの2つの行があり、ユーザーが正しく入力すると、正しいページにリダイレクトする必要があります。しかし、私がボタンを押すと何も起こりません、私はここで何が間違っていますか?ログインフォームの検証ASP.NET MVC

モデル:

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

あなたがasp.netでの認証と承認を学びたいのであれば、入力タイプ=ボタン – CodeConstruct

+0

を取るブログやユーチューブの動画で探してください。 はまた、次の記事をお読みください。この質問を削除してください。 –

+2

あなたのコードには何の意味もありません。 MVCのサイトに行って、チュートリアルを通して基本を学ぶことを強くお勧めします。 –

答えて

4

あなたは正しい軌道に乗っているが、問題のカップルはつまり、あなたのコードであります:

  • ビューはコントローラでValidate()アクションを呼び出していません。
  • データベースに接続するためのADO.NETロジックは完全に間違っています。
  • SQLクエリにWHERE句が含まれていません。
  • MVCが提供する[AllowAnonymous][Authorize]の認証属性を使用していません。

    1.Web.config:(<configuration>下)のWeb.configで

    1.1Add <connectionStrings>要素:

    あなたはあなたのコードに次の変更を加える必要があり

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

1.2 Web.Config(<system.web>)の<authentication>要素を追加してください:

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

2.Decorate [Authorize]

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

3.LoginControllerであなたにHomeController:

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 [email protected] 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インデックスビュー:

MVC forms authentication by Jon Galloway

+0

それはうまくいかなかった。 – Malphai

+0

どの部分がうまくいかなかったのですか?私は自分の側でテストしたので、うまく動いています。 –

+0

こんにちは。私の場合は、ホームコントローラの上のAuthorize属性に関する部分が機能しませんでした。 FormsAuthentication.SetAuthCookieを設定しましたが、ホームインデックスにリダイレクトされたときにHTTPエラー401.0 - 権限がありませんでした。私は何が欠けていますか?ありがとう –