我的解决方案中有两个项目,UI 作为 mvc 和首先用于实体模型代码的类项目。我的模型中有多个实体,但现在我需要通过新的审计字段来扩展它们,我需要保存谁更改了实体。
我添加了新界面
public interface IAuditable
{
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
DateTime CreatedDate { get; set; }
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
string CreatedBy { get; set; }
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
DateTime UpdatedDate { get; set; }
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
string UpdatedBy { get; set; }
}
并尝试以这种方式扩展 SaveChanges
foreach (var auditableEntity in ChangeTracker.Entries<IAuditable>())
{
if (auditableEntity.State == EntityState.Added ||
auditableEntity.State == EntityState.Modified)
{
// implementation may change based on the useage scenario, this
// sample is for forma authentication.
string currentUser = ;
// modify updated date and updated by column for
// adds of updates.
auditableEntity.Entity.UpdatedDate = DateTime.Now;
auditableEntity.Entity.UpdatedBy =
// pupulate created date and created by columns for
// newly added record.
if (auditableEntity.State == EntityState.Added)
{
auditableEntity.Entity.CreatedDate = DateTime.Now;
auditableEntity.Entity.CreatedBy = currentUser;
}
else
{
auditableEntity.Property(p => p.CreatedDate).IsModified = false;
auditableEntity.Property(p => p.CreatedBy).IsModified = false;
}
}
但我如何在这里获取用户名?我无法使用任何 httpContex getUser 因为这是类项目。有任何想法吗?
这是我的背景
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbContext
所以我想通过 LogedUserName 等另一个字段扩展 ApplicationUser ,并在用户登录时填充它,但是如何在 SaveChanges 方法中获取此字段?
如果您确定该类库将始终在 ASP.NET 管道中使用,您实际上可以访问HttpContext
。
您需要参考System.Web
在你的类库中,然后:
using System.Web;
[...]
public void SaveChanges()
{
var username = HttpContext.Current.User.Identity.Name;
}
在这种情况下HttpContext
是静态类,而不是属性。
当然,如果此类在 ASP.NET 管道之外使用(例如在 WPF 应用程序、控制台应用程序等中),这将严重失败。而且这样做似乎也不干净。但这可能是最快的方法,需要最少的现有代码更改。
另一种方法是将用户名或整个身份传递给负责保存更改的类或直接传递给SaveChanges
method.
一种实现可能如下所示:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbContext
{
private IPrincipal _currentUser;
public ApplicationDbContext(IPrincipal currentUser)
{
_currentUser = currentUser;
}
}
然后在 Controller 中(如果直接在 MVC 控制器中使用上下文):
using(var db = new ApplicationDbContext(User))
{
[...]
}
where User
是持有当前用户的控制器的属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)