iT邦幫忙

0

帳號登入系統一直顯示帳號或密碼錯誤??

  • 分享至 

  • xImage

最近在接觸C# MVC和Vue的功能開發,參考範例並在練習帳號登入系統功能的,但實在是不知道為何一直顯示錯誤訊息,顯示帳號或密碼錯誤,debug很久還是想不通為何傳進來的資料為null所以等同於沒資料傳進來,還煩請各位前輩指導,感謝感謝!
底下是我的code,還請糾正一番.

Models:

public class Member
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [Required]
        [Display(Name = "帳號")]
        [StringLength(30,ErrorMessage = "請輸入帳號")]
        public string Account { get; set; }

        [Required]
        [Display(Name = "姓名")]
        [StringLength(20, ErrorMessage = "請輸入姓名")]
        public string Name { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "密碼")]
        [StringLength(255, ErrorMessage = "請輸入密碼,至少要6個字元", MinimumLength = 6)]
        public string Pwd { get; set; }

        [Required]
        [Display(Name = "單位")]
        [StringLength(20, ErrorMessage = "請輸入單位")]
        public string Teams { get; set; }

        [Required]
        [Display(Name = "分機號碼")]
        [StringLength(20, ErrorMessage = "請輸入分機號碼")]
        public string Ext { get; set; }

        [Required]
        [Display(Name = "電子信箱")]
        [StringLength(30, ErrorMessage = "請輸入Email")]
        [EmailAddress(ErrorMessage = "非Email格式")]
        public string Email { get; set; }

        [Display(Name = "權限")]
        public int Permission { get; set; }

        public class DoLoginIn
        {
            public string UserID { get; set; }
            public string UserPwd { get; set; }
        }

        public class DoLoginOut
        {
            public string ErrMsg { get; set; }
            public string ResultMsg { get; set; }
        }

    }

Controler:

 public class LoginController : Controller
    {
        public ActionResult Login()
        {
            return View();
        }

        public ActionResult DoLogin(DoLoginIn inModel)
        {
            DoLoginOut outModel = new DoLoginOut();

            if (string.IsNullOrEmpty(inModel.UserID) || string.IsNullOrEmpty(inModel.UserPwd))
            {
                outModel.ErrMsg = "請輸入資料";
            }
            else
            {
                SqlConnection conn = null;

                try
                {
string connStr = System.Web.Configuration.WebConfigurationManager.ConnectionStrings[""].ConnectionString;
                    conn = new SqlConnection();
                    conn.ConnectionString = connStr;
                    conn.Open();

string salt = inModel.UserID.Substring(0, 1).ToLower(); 
SHA256 sha256 = SHA256.Create();
byte[] bytes = Encoding.UTF8.GetBytes(salt + inModel.UserPwd); 
byte[] hash = sha256.ComputeHash(bytes);
StringBuilder result = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
      {
          result.Append(hash[i].ToString("X2"));
      }
          string CheckPwd = result.ToString(); 
string sql = "select * from Members where Account = @Account and Pwd= @Pwd";
          SqlCommand cmd = new SqlCommand();
          cmd.CommandText = sql;
          cmd.Connection = conn;                   
          cmd.Parameters.AddWithValue("@Account", inModel.UserID);
          cmd.Parameters.AddWithValue("@Pwd", CheckPwd); 
       
          SqlDataAdapter adpt = new SqlDataAdapter();
          adpt.SelectCommand = cmd;
          DataSet ds = new DataSet();
          adpt.Fill(ds);

  if (ds.Tables[0].Rows.Count > 0)
          {
             Session["UserID"] = inModel.UserID;

             outModel.ResultMsg = "登入成功";
          }
  else
          {
             outModel.ErrMsg = "帳號或密碼錯誤";
           }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (conn != null)
                    {
                        //關閉資料庫連線
                        conn.Close();
                        conn.Dispose();
                    }
                }
            }
            return Json(outModel);
        }
	}

View:

<div id="VuePage">
    <div class="panel panel-primary">
        <div class="panel-heading">登入頁面</div>
        <div class="panel-body">
            <div class="form-group">
<input type="text" class="form-control" v-model="form.UserID">
            </div>
            <div class="form-group">
                <label>密碼</label>
<input type="password" class="form-control" v-model="form.UserPwd">
            </div>
        </div>
        <div class="panel-footer">
<button type="button" class="btn btn-primary" v-on:click="DoLogin()">登入</button>
        </div>
    </div>

    <!--當執行有錯誤時,顯示錯誤訊息-->
    <div class="modal fade" id="ErrorAlert" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">錯誤訊息</h4>
                </div>
                <div class="modal-body" id="ErrorMsg" style="overflow-x:auto;width:100%;">

                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
</div>
@section scripts {
    <script>
        var VuePage = new Vue({
            el: '#VuePage'
            , data: function () {
                var data = {
                    form: {}
                };
                return data;
            }
            , methods: {

                DoLogin: function () {
                    var self = this;

                    var postData = {};
                    postData['UserID'] = self.form.UserID;
                    postData['UserPwd'] = self.form.UserPwd;

                    $.ajax({
                        url:'@Url.Content("~/Login/DoLogin")',
                        method:'POST',
                        dataType:'json',
                        data: { inModel: postData },
                        
                        success: function (datas) {
                            console.log(datas);
                            debugger;
                            if (datas.ErrMsg) {
                                alert(datas.ErrMsg);
                                return;
                            }
                            alert(datas.ResultMsg);
                        },
                        error: function (err) {
                            $('#ErrorMsg').html(err.responseText);
                            $('#ErrorAlert').modal('toggle');
                        },
                    });
                }
            }
        })
    </script>
}
w4560000 iT邦研究生 5 級 ‧ 2022-04-13 11:06:08 檢舉
我測試是正常耶,能傳你的專案到Github嗎?
我Clone下來看看
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答