如何覆盖ServiceStack RegistrationService Validator?

时间:2013-11-06 01:35:42

标签: servicestack

如何覆盖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>()));

1 个答案:

答案 0 :(得分: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>>();
    }
}