[英]Do I need a database to save a finite set of data, and only for the current session in an ASP.NET MVC app?
[英]How do I save Log In session in ASP.NET MVC
嗨,這是我登錄頁面的登錄 Controller,我已經完成了所有檢查和登錄,但是我沒有登錄 Session,所以我的網站不知道誰使用數據庫中的 ID 和密碼登錄。 因此,即使在登錄后,該網站也只能識別一個用戶。
如果我要使用按鈕進行選擇,我還需要知道如何檢索登錄 session。 例如; “用戶 Z 選擇WorkSchedule
A *使用用戶 Z 的用戶名和密碼登錄后”
如果網站沒有保存 session,則登錄將不完整,我在保存 session 時遇到了麻煩,如果有人能指導我制作它,我將不勝感激。
Controller 代碼:
[HttpGet]
public ActionResult Login()
{
return View();
}
void connectionString()
{
con.ConnectionString = " ";
}
[HttpPost]
public ActionResult SaveData(Account acc)
{
connectionString();
con.Open();
com.Connection = con;
com.CommandText = "insert into Staff (StaffNRIC,StaffEmail,StaffContact,StaffName,StaffAddress,BranchID,StaffRole,StaffPositionID,StaffAccountStatus)" +
"values ('" + acc.StaffNRIC + "','" + acc.StaffEmail + "','" + acc.StaffContact + "','" + acc.StaffName + "','" + acc.StaffAddress + "','" + acc.BranchID + "',' NULL ','" + acc.StaffPositionID + "', 'Pending' )";
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
return View("Register");
}
else
{
con.Close();
return View("Login");
}
}
[HttpPost]
public ActionResult Verify(Account acc)
{
connectionString();
con.Open();
com.Connection = con;
com.CommandText = "select * from Staff where StaffNRIC='" + acc.StaffNRIC + "' and StaffContact='" + acc.StaffContact + "' and StaffAccountStatus = 'Approved'";
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
return View("Home");
}
else
{
con.Close();
return View("Login");
}
}
查看頁面:
<form action="Verify" method="post">
<div class=" w3l-form-group">
<label>NRIC:</label>
<div class="group">
<i class="fas fa-user"></i>
<input type="text" name="StaffNRIC" class="form-control" placeholder="StaffNRIC" required="required">
</div>
</div>
<div class=" w3l-form-group">
<label>Password:</label>
<div class="group">
<i class="fas fa-unlock"></i>
<input type="password" name="StaffContact" class="form-control" placeholder="StaffContact" required="required">
</div>
</div>
<button type="submit">Login</button>
</form>
</div>
首先,根據您的描述,您的應用程序似乎是 Asp.net MVC 應用程序,而不是 Asp.net Core MVC 應用程序。 因此,您可以直接使用 session 將用戶信息存儲在 session 中:
代碼如下,將值保存到 session:
Session("UserName") = UserName;
然后,當您從 session 讀取數據時,您可以使用以下代碼:
if (Session["UserName"] != null)
{
return View();
} else
{
return RedirectToAction("Login");
}
關於 asp.net 中的 session state 管理的更多詳細信息,請查看以下文章:
其次,Asp.net提供了一個Identity system,我們可以使用它的內置方法來實現Login function,Manager用戶,角色等,並通過cookie存儲登錄用戶信息。 您可以嘗試將它與您的 MVC 應用程序一起使用。 請檢查以下文章:
將 ASP.NET 身份添加到空的或現有的 Web Forms 項目
此外,如果您的應用程序是 Asp.net Core MVC 應用程序,則必須在 Startup.cs 中啟用 session 中間件。 有關在 asp.net 內核中使用 session 和 Identity 的更多詳細信息,您可以查看以下文章:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.