Entity Framework get user from contex in saveChanges

a 夏天 提交于 2019-12-06 11:27:13

If you are sure that this class library will be always used in ASP.NET pipeline you actually can access HttpContext. You need a reference to System.Web in your class library and then:

using System.Web;
[...]
public void SaveChanges()
{
    var username = HttpContext.Current.User.Identity.Name;
}

In this case HttpContext is a static class, not a property.

Ofcourse this will fail badly if this class is ever used outside ASP.NET pipeline (for example in WPF application, console app etc). Also it doesn't seem clean to do it this way. But it's probably the fastest way which requires minimal existing code change.

Another way would be to pass either username or whole identity to either class responsible for saving changes or directly to SaveChanges method.

One implementation could look like this:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbContext
{
    private IPrincipal _currentUser;
    public ApplicationDbContext(IPrincipal currentUser)
    {
        _currentUser = currentUser;
    }
}

and then in Controller (if you use context directly in MVC controllers):

using(var db = new ApplicationDbContext(User))
{
    [...]
}

where User is controller's property holding current user.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!