2

我想知道从我们通过 servicestack 的 fluent-validation API 挂钩连接的自定义验证器中访问用户AuthSession的最佳方式。基本上,要求迫使我们使用名为“ DocNumberValidator ”的类通过该验证器访问数据库。用户的 ID 在他们进行身份验证时保存到会话中,我们需要此信息来完成成功的 SQL 查询。如何访问此会话信息(见下文....)。IoC 容器没有对 AuthSession 的引用?

  • 我想问题是,有人如何将必要的会话值传递给 SS 验证框架调用的类

示例代码:


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;
    }
}
4

1 回答 1

1

不太确定这是最好的方法。接受建议。

  • 使用 SessionFeature.GetSessionKey() 获取会话密钥
  • 添加public ICacheClient CacheClient { get; set; }到验证器。将由 IoC 容器注入
  • 使用密钥从缓存中获取 AuthUserSession(或您正在使用的任何类型)

添加到您的示例中

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;
    }
}
于 2013-04-23T21:23:41.060 回答