在ServiceStack中使用Fluent Validation没有错误消息
本文关键字:Validation 有错误 消息 Fluent ServiceStack | 更新日期: 2023-09-27 18:01:48
我刚刚开始熟悉ServiceStack,并遇到了FluentValidation。我按照介绍创建了一个小Hello App。
我的问题是,当我尝试验证请求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();
}
}
}
注:真的很喜欢使用ServiceStack,它真的是一个了不起的项目,所以谢谢。
编辑
例如:
Calling: http://localhost:60063/hello/Ian?format=json
返回{"Result":"Hello, Ian"}
。而调用:http://localhost:60063/hello/I?format=json
返回{}
。
第二个调用返回{}
,我期望自动生成错误消息。
我找到了答案。这对我来说是一个疏忽:
这是在文档中,我忽略了它:
因此,我的代码中所缺少的就是将以下行添加到处理下面描述的所有错误处理和验证选项的ResponseStatus属性中序列化响应DTO使您的客户端应用程序能够一般以相同的方式处理所有Web服务错误。
HelloResponse
类中。
public ResponseStatus ResponseStatus {get;设置;}