1

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

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

应用主机代码:

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

1 回答 1

2

对,ServiceStack 会在服务被调用之前验证请求 DTO(如果ValidationFeature启用)。

要在服务中手动调用验证器,您必须从AppHost第一行中删除此行:

Plugins.Add(new ValidationFeature());

请确保您的服务中的验证器属性具有 type IValidator<>,否则如果您使用container.RegisterValidators(typeof(AddBookingLimitValidator).Assembly).

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

    public RequestResponse Post(Request request)
    {
        Validator.Validate(request); 
        ...
    }
}
于 2013-04-05T13:50:59.553 回答