4

如何覆盖 ServiceStack RegistrationService Validator 并向其添加一些新规则?

需要做什么来拦截 UserAuthService 验证?

这是 AppHost 配置:

  Plugins.Add(new CorsFeature()); //Registers global CORS Headers

  RequestFilters.Add((httpReq, httpRes, requestDto) =>
  {
    // Handles Request and closes Responses after emitting global HTTP Headers
    if (httpReq.HttpMethod == "OPTIONS")
      httpRes.EndRequest();
  });

  // Enable the validation feature
  Plugins.Add(new ValidationFeature());

  // This method scans the assembly for validators
  container.RegisterValidators(typeof(AppHost).Assembly);

  container.Register<ICacheClient>(new MemoryCacheClient());

  //var dbFactory = new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider);
  var dbFactory = new OrmLiteConnectionFactory(connectionString, SqliteDialect.Provider);

  container.Register<IDbConnectionFactory>(dbFactory);

  // Enable Authentication
  Plugins.Add(new AuthFeature(() => new CustomUserSession(),
    new IAuthProvider[] {
            new CustomAuthProvider(), 
        }));

  // Provide service for new users to register so they can login with supplied credentials.
  Plugins.Add(new RegistrationFeature());

  // Override the default registration validation with your own custom implementation
  container.RegisterAs<CustomRegistrationValidator, IValidator<Registration>>();

  container.Register<IUserAuthRepository>(c => new CustomAuthRepository(c.Resolve<IDbConnectionFactory>()));
4

1 回答 1

4

ServiceStack 验证器非常易于使用。“SocialBootstrap”示例展示了如何使用自定义验证器在其AppHost.cs中进行注册。

//Provide extra validation for the registration process
public class CustomRegistrationValidator : RegistrationValidator
{
    public CustomRegistrationValidator()
    {
        RuleSet(ApplyTo.Post, () => {
            RuleFor(x => x.DisplayName).NotEmpty();
        });
    }
}

请记住也要注册您的自定义验证器。

//override the default registration validation with your own custom implementation
container.RegisterAs<CustomRegistrationValidator, IValidator<Registration>>();

使用“RuleSet”添加更多规则。希望有帮助。

编辑 似乎在当前 v3 版本的 ServiceStack 中可能存在阻止调用验证器的错误。我对 Social Bootstrap 项目进行了快速测试,并且可以重现您所遇到的情况,例如 CustomRegistrationValidator 没有触发其规则。其他验证器似乎工作正常,所以目前不确定原因可能是什么。当我有时间时,我会拉下源代码进行调试。如果您碰巧事先这样做,请张贴您发现的内容,因为它可能对其他人有所帮助。

更新 这个问题是由于插件和注册的操作顺序造成的。注册插件在注册后运行它的Register功能CustomRegistrationValidator并覆盖注册为IValidator<Registration>.

解决这个问题的最简单方法是创建自己的 RegistrationFeature,因为它本身非常简单。

public class MyRegistrationFeature : IPlugin
{
    public string AtRestPath { get; set; }

    public RegistrationFeature()
    {
        this.AtRestPath = "/register";
    }

    public void Register(IAppHost appHost)
    {
        appHost.RegisterService<RegisterService>(AtRestPath);
        appHost.RegisterAs<CustomRegistrationValidator, IValidator<Registration>>();
    }
}
于 2013-11-06T03:44:07.190 回答