业务逻辑层 - 获取当前用户

时间:2014-12-24 11:53:34

标签: c# asp.net architecture

我有一个业务逻辑层和2个使用它的应用程序,一个MVC UI和一个Web API项目。

我的类中的一个属性是CreatedBy和UpdatedBy,它应该包含用户ID。

    public Nullable<System.DateTime> CreatedTS { get; set; }
    public string CreatedBy { get; set; }
    public Nullable<System.DateTime> UpdatedTS { get; set; }
    public string UpdatedBy { get; set; }

鉴于BLL有多个消费者,捕获userId的最佳方式是什么?

A) - 使用Environment.UserName

在BLL中设置此项

B) - 要求客户设置它并使用模型数据注释使其成为必需

C) - 要求客户将其传递给BLL中的任何Create或Update方法。

2 个答案:

答案 0 :(得分:2)

我通常会使用Thread.CurrentPrincipal.Identity.Name

为此,您必须确保Thread.CurrentPrincipal设置为代表当前用户的主体。这是在UI层中完成的,并且如果您:

将自动发生

答案 1 :(得分:1)

如果您在MVC和WebApi中都使用FormsAuthentication,则可以访问属性User.Identity.Name

int userId = db.Users.Single(r=>r.Name == User.Identity.Name);

在WebApi中,它将是HttpContext.Current.User.Identity.Name

这种方法非常安全。如果您在客户端存储userId,则用户可以对其进行修改。