[英]Retrieving the current logged in user's Id in a class library outside of an ASP.NET Webforms App using forms authentication
當前,在我的每個模型類中,我都在構造函數中執行以下操作。
public Product()
{
CreatedBy = System.Threading.Thread.CurrentPrincipal.Identity.Name;
ModifiedBy = System.Threading.Thread.CurrentPrincipal.Identity.Name;
}
這樣,在保存/更新記錄時,將始終設置這些值。
但是,我想將我的應用程序從上面獲取的登錄用戶名切換為使用登錄用戶ID。
使用表單身份驗證,什么是不使用Session來檢索有關當前登錄用戶的其他數據的最佳方法是什么? 我注意到您可以在用戶登錄后立即創建表單身份驗證cookie時傳遞其他數據,但是我不知道如何檢索它。
這是我想出的解決方案。 我將不勝感激任何意見或建議。 每當我在UI上創建這些模型對象之一時,我都需要在構造函數中傳遞userId,這感覺有點奇怪:
public abstract class AuditableEntity : BaseEntity
{
public DateTime CreatedDate { get; set; }
public int? CreatedBy { get; set; }
public DateTime ModifiedDate { get; set; }
public int? ModifiedBy { get; set; }
}
public class Product : AuditableEntity
{
public User(int userId)
{
this.CreatedBy = userId;
this.ModifiedBy = userId;
}
public string ProductName { get; set; }
public string SerialNumber { get; set; }
}
驗證用戶身份時,用戶可以使用FormsAuthenticationTicket向其傳遞所有cookie信息和其他userData(字符串), 這是一個示例 ,然后通過以下方式進行檢索:
FormsIdentity id = (FormsIdentity)User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
//those are label ids, that why they have Text property
cookiePath.Text = ticket.CookiePath;
expireDate.Text = ticket.Expiration.ToString();
expired.Text = ticket.Expired.ToString();
isPersistent.Text = ticket.IsPersistent.ToString();
issueDate.Text = ticket.IssueDate.ToString();
name.Text = ticket.Name;
userData.Text = ticket.UserData; // string userData you passed is HERE
version.Text = ticket.Version.ToString();
順便說一句,你應該使用HttpContext.Current.User.Identity.Name
,看看這個和這個 ,也許這個問題 。
您提到了很多具有這些CreatedBy和ModifiedBy屬性的類。
讓他們實現一個接口:
interface IAuditableEntity
{
int CreatedBy {get; set;}
int ModifiedBy {get; set;}
}
public class Product : IAuditableEntity
{
public string ProductName { get; set; }
public string SerialNumber { get; set; }
public int CreatedBy {get; set;}
public int ModifiedBy {get; set;}
}
public class Vendor : IAuditableEntity
{
public string VendorName{ get; set; }
public string VendorNumber { get; set; }
public int CreatedBy {get; set;}
public int ModifiedBy {get; set;}
}
在Web應用程序中創建一個集中位置,該位置負責與BLL進行通信,該BLL為您設置了這些屬性。
public class BllLink
{
public static void SaveEntity(IAuditableEntity entity)
{
entity.ModifiedBy = HttpContext.Current.User.Identity.Name;
if(String.IsNullOrEmpty(entity.CreatedBy)) //assume new
{
entity.CreatedBy = HttpContext.Current.User.Identity.Name;
}
Bll.SaveEntity(entity); //you might need to use generics
}
}
當您看到重復的代碼時,它是簡化的理想選擇。 學習如何有效利用泛型和接口將大大有助於這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.