ServiceStack验证功能引发异常

时间:2013-04-05 13:13:29

标签: servicestack

我正在尝试在ServiceStack中实现验证功能,以便在调用db操作之前验证我的RequestDTO。 当我尝试验证请求时

ValidationResult result = this.AddBookingLimitValidator.Validate(request);

代码会自动自动抛出验证错误。 我甚至无法调试服务幕后发生的事情?我可以改变这种行为,或者我在这里做错了什么。 感谢。

我的要求DTO:

[Route("/bookinglimit", "POST")]
[Authenticate]
public class AddBookingLimit : IReturn<AddBookingLimitResponse>
{       
  public int ShiftId { get; set; }
  public DateTime Date { get; set; }
  public int Limit { get; set; }
}

我的回复DTO:

public class AddBookingLimitResponse
{
  public int Id { get; set; }
  public ResponseStatus ResponseStatus { get; set; }
}

验证类:

public class AddBookingLimitValidator : AbstractValidator<AddBookingLimit>
{
  public AddBookingLimitValidator()
  {
    RuleFor(r => r.Limit).GreaterThan(0).WithMessage("Limit 0 dan büyük olmalıdır");
  }
}

服务实施:

public AddBookingLimitResponse Post(AddBookingLimit request)
{
  ValidationResult result = this.AddBookingLimitValidator.Validate(request);          

  Shift shift = new ShiftRepository().Get(request.ShiftId);
  BookingLimit bookingLimit = new BookingLimit
  {
    RestaurantId = base.UserSession.RestaurantId,
    ShiftId = request.ShiftId,
    StartDate = request.Date.AddHours(shift.StartHour.Hour).AddMinutes(shift.StartHour.Minute),
    EndDate = request.Date.AddHours(shift.EndHour.Hour).AddMinutes(shift.EndHour.Minute),
    Limit = request.Limit,
    CreateDate = DateTime.Now,
    CreatedBy = base.UserSession.UserId,
    Status = (byte)Status.Active
  };
  return new AddBookingLimitResponse
  {
    Id = new BookingLimitRepository().Add(bookingLimit)
  };
        }

AppHost代码:

container.RegisterValidators(typeof(AddBookingLimitValidator).Assembly);
Plugins.Add(new ValidationFeature());

我在c#代码中使用该服务:

 try
 {
   AddBookingLimitResponse response = ClientHelper.JsonClient.Post(new AddBookingLimit
   {
     Date = DateTime.Parse(DailyBookingLimitDateTextBox.Text),
     Limit = Convert.ToInt32(DailyBookingLimitTextBox.Text),
     ShiftId = Convert.ToInt32(DailyDayTypeSelection.SelectedValue)
    });
    WebManager.ShowMessage(UserMessages.SaveSuccessful.FormatString(Fields.BookingLimit));
  }
  catch (WebServiceException ex)
  {
    WebManager.ShowMessage(ex.ResponseStatus.Message);           
  }

1 个答案:

答案 0 :(得分:2)

是的,如果启用了ValidationFeature,ServiceStack会在调用服务之前验证请求DTO。

要手动调用服务中的验证程序,您必须先从AppHost删除此行:

Plugins.Add(new ValidationFeature());

请确保您服务中的validator属性具有IValidator<>类型,否则如果您使用container.RegisterValidators(typeof(AddBookingLimitValidator).Assembly)注册验证器,则IoC容器不会注入该属性。

public class TestService : Service
{
    public IValidator<Request> Validator { get; set; }

    public RequestResponse Post(Request request)
    {
        Validator.Validate(request); 
        ...
    }
}