2013-03-01 73 views
2

我刚刚开始熟悉ServiceStack,并且遇到了FluentValidation。我遵循了介绍并创建了一个小的Hello应用程序。在ServiceStack中没有错误消息与Fluent验证

我的问题是,当我尝试验证请求DTO 没有错误消息返回来形容它是如何验证失败,只有一个空的JSON对象{}

我自己,我认为验证是自动装配到DTO,所以应该不需要我写任何额外的代码。

答案可能是公然的,但我看不到它。任何帮助将不胜感激。我的代码如下:

namespace SampleHello2 
{ 
    [Route("/hello")] 
    [Route("/hello/{Name}")] 
    public class Hello 
    { 
     public string Name { get; set; } 
    } 

    public class HelloResponse 
    { 
     public string Result { get; set; } 
    } 


    public class HelloService : Service 
    { 
     public object Any(Hello request) 
     { 
      return new HelloResponse { Result = "Hello, " + request.Name }; 
     } 
    } 

    public class HelloValidator : AbstractValidator<Hello> 
    { 
     public HelloValidator() 
     { 
      //Validation rules for all requests 
      RuleFor(r => r.Name).NotNull().NotEmpty().Equal("Ian").WithErrorCode("ShouldNotBeEmpty"); 
      RuleFor(r => r.Name.Length).GreaterThan(2); 
     } 
    } 

    public class Global : System.Web.HttpApplication 
    { 
     public class HelloAppHost : AppHostBase 
     { 
      //Tell Service Stack the name of your application and where to find your web services 
      public HelloAppHost() : base("Hello Web Services", typeof(HelloService).Assembly) { } 

      public override void Configure(Funq.Container container) 
      { 
       //Enable the validation feature 
       Plugins.Add(new ValidationFeature()); 
       container.RegisterValidators(typeof(HelloValidator).Assembly); 
       //register any dependencies your services use, e.g: 
       // container.Register<ICacheClient>(new MemoryCacheClient()); 
      } 
     } 

     //Initialize your application singleton 
     protected void Application_Start(object sender, EventArgs e) 
     { 
      new HelloAppHost().Init(); 
     } 
    } 
} 

P.S.真的很享受使用ServiceStack,这真的是一个梦幻般的项目,所以谢谢。

编辑

因此,例如:

呼叫:http://localhost:60063/hello/Ian?format=json回报{"Result":"Hello, Ian"}。 鉴于调用:http://localhost:60063/hello/I?format=json返回{}

第二个调用返回{}我期待自动生成的错误消息。

回答

6

我找到了答案。这是代表我的不注意:

这是在文档中,我忽略了它:下述

所有错误处理和验证选项被视为 以同样的方式 - 序列化到的ResponseStatus财产您的 响应DTO使您的客户端应用程序能够以相同的方式统一处理所有Web服务错误。

因此,我的代码中缺少的部分是将以下行添加到HelloResponse类中。

public ResponseStatus ResponseStatus {get;组; }

+1

另外,当使用[ServiceStack的新API](https://github.com/ServiceStack/ServiceStack/wiki/New-Api)时,ResponseStatus属性只有在Response DTO遵循被命名的约定时才需要'RequestDtoResponse',因为这是DTO ServiceStack将水合错误。如果没有响应DTO存在ServiceStack将使用通用** **错误响应DTO(即的,而不是你的反应DTO)已经具有了'ResponseStatus'财产。 – mythz 2013-03-01 17:07:40