[英]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.