使用表单身份验证在 ASP.NET Webforms 应用程序之外的 class 库中检索当前登录用户的 ID

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;
    }

这样当 saving/updating 记录时,这些值将始终被设置。

但是,我想将我的应用程序从使用上面得到的登录用户名切换到使用登录用户的 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; }
}

认证用户时,user可以使用FormsAuthenticationTicket将所有cookie信息和附加的userData(字符串)传递给它,here is an example,然后通过以下方式检索:

       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();

More information

对了,你应该用HttpContext.Current.User.Identity.Name,看看this and this maybe this question

您提到您有很多 类 具有这些 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 通信。

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
    }
}

当您看到重复代码时,很适合进行简化。学习如何有效地利用泛型和接口将大有帮助。