3

我刚刚开始熟悉 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();
        }
    }
}

PS 真的很喜欢使用 ServiceStack,这真的是一个很棒的项目,非常感谢。

编辑

例如:

调用:http://localhost:60063/hello/Ian?format=json返回{"Result":"Hello, Ian"}。而调用:http://localhost:60063/hello/I?format=json返回{}

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

4

1 回答 1

7

I found the answer. It was an overlook on my behalf:

This was in the documentation and I overlooked it:

All Error handling and validation options described below are treated in the same way - serialized into the ResponseStatus property of your Response DTO making it possible for your clients applications to generically treat all Web Service Errors in the same way.

So all that was missing from my code was to add the following line into the HelloResponse class.

public ResponseStatus ResponseStatus { get; set; }

于 2013-03-01T15:08:26.540 回答