我想知道从我们通过servicestack的fluent-validation API挂钩连接的自定义验证器中访问用户的 AuthSession 的最佳方法。基本上,这些要求迫使我们使用名为“ DocNumberValidator ”的类通过此验证器访问数据库。用户的身份验证在身份验证时保存到会话中,我们需要此信息才能完成成功的SQL查询。如何访问此会话信息(见下文....)。 IoC容器没有引用AuthSession?
示例代码:
public class MyValidator : AbstractValidator<Statuses>
{
public IDocNumberValidator DocNumberValidator { get; set; }
public StatusesValidator()
{
RuleFor(s => s.DocNumber)
.Must(docNum => this.DocNumberValidator.Validate(docNum))
.WithMessage("Document Number is invalid.")
.WithErrorCode("S-001");
}
}
public class DocNumberValidator : IDocNumberValidator
{
public IDbConnectionFactory Db { get; set; }
public bool Validate(string docNum)
{
var isFound = false;
this.Db.Run(conn =>
{
var sql = "SELECT COUNT([docNumber]) FROM [TABLE] WHERE [docNumber] = @DocNum AND [UserId] = @UserID";
var cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.Add(new SqlParameter("@DocNum", docNum));
cmd.Parameters.Add(new SqlParameter("@UserID", ????????)); // how does one get access to saved users session here
int cnt = (int) cmd.ExecuteScalar();
if (cnt == 1)
isFound = true;
});
return isFound;
}
}
答案 0 :(得分:1)
不确定这是最好的方法。接受建议。
public ICacheClient CacheClient { get; set; }
添加到验证程序。
将由IoC容器注入已添加到您的示例中
public class DocNumberValidator : IDocNumberValidator
{
public IDbConnectionFactory Db { get; set; }
public ICacheClient CacheClient { get; set; }
public bool Validate(string docNum)
{
var isFound = false;
var sessionKey = SessionFeature.GetSessionKey();
var user = CacheClient.Get<AuthUserSession>(sessionKey); //Use whatever class you stored in the session
this.Db.Run(conn =>
{
var sql = "SELECT COUNT([docNumber]) FROM [TABLE] WHERE [docNumber] = @DocNum AND [UserId] = @UserID";
var cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.Add(new SqlParameter("@DocNum", docNum));
cmd.Parameters.Add(new SqlParameter("@UserID", user.UserAuthId)); // user whatever property you need access to
int cnt = (int) cmd.ExecuteScalar();
if (cnt == 1)
isFound = true;
});
return isFound;
}
}