我们最近为我们的数据库添加了审计功能。一位同事使用触发器实现了这个功能,并要求我在网站登录时调用一个存储过程。该存储过程将当前用户名和当前Oracle会话ID插入到一个表中,以便触发器可以将会话ID映射到用户名。问题是(或者曾经是),他假设用户的互联网会话映射到数据库会话。这并不是事实,而且我们使用连接池,因此Oracle会话ID可以映射到许多用户,而不一定是在该会话上登录的用户。
因此,我在我的数据访问层中创建了一个实用方法,在每次插入、更新和删除时调用他的存储过程(确保它在同一事务中)。
这个方法可以正常工作,审计功能也按要求工作。但是,我不喜欢调用HttpContext:
因此,我在我的数据访问层中创建了一个实用方法,在每次插入、更新和删除时调用他的存储过程(确保它在同一事务中)。
/// <summary>
/// Performs an insert, update or delete against the database
/// </summary>
/// <param name="transaction"></param>
/// <param name="command">The command.</param>
/// <param name="transaction">A transaction, can be null.
/// No override provided without a transaction, to remind developer to always consider transaction for inserts, updates and deletes</param>
/// <returns>The number of rows affected by the operation</returns>
public static int InsertUpdateDelete(OracleCommand command, OracleTransaction transaction)
{
if (command == null)
throw new ArgumentNullException("command", "command is null.");
OracleConnection connection = null;
bool doCommit = false;
try
{
if (transaction == null)
{
//We always need a transaction for the audit insert
connection = GetOpenConnection();
transaction = connection.BeginTransaction();
doCommit = true;
}
command.Transaction = transaction;
command.Connection = transaction.Connection;
//TODO HttpContext requires that presentation layer is a website. So this call should NOT be in the data access layer.
string username = HttpContext.Current.User.Identity.Name;
if (!String.IsNullOrEmpty(username))
pInsertCurrentUserForAudit(username, command.Transaction);
int recordsAffected = command.ExecuteNonQuery();
if (doCommit)
transaction.Commit();
return recordsAffected;
}
finally
{
if (doCommit)
{
if (transaction != null)
transaction.Dispose();
if (connection != null)
connection.Dispose();
}
}
}
这个方法可以正常工作,审计功能也按要求工作。但是,我不喜欢调用HttpContext:
string username = HttpContext.Current.User.Identity.Name;
这是最快实现任务的方法,但我认为它不应该在数据访问层中操作。如果未来某个时候我想使用窗体应用程序访问数据库,那么当我访问HttpContext时会出现错误吗? 有没有更好的方法来获取用户名并正确分离其职责?将用户名作为参数传递到每个插入、更新和删除操作中是一种选择,但这将是一个繁琐的任务,我想知道有没有更优雅的方法。