【问题标题】:Is ResponseStatus needed in ServiceStack?ServiceStack 中是否需要 ResponseStatus?
【发布时间】:2012-07-29 20:24:43
【问题描述】:

是否需要 ResponseStatus?

wiki 说我们需要在响应 DTO 中有一个 ResponseStatus 属性来处理异常序列化:

https://github.com/ServiceStack/ServiceStack/wiki/Validation

但是看起来 ResponseStatus 是自动生成的,即使响应 DTO 中没有 ResponseStatus 属性。

我们需要 ResponseStatus 属性吗?

【问题讨论】:

    标签: c# error-handling servicestack


    【解决方案1】:

    Error Handling Docs 解释了如何控制哪些服务返回填充的ResponseStatus DTO,即:

    错误响应类型

    抛出异常时返回的错误响应取决于是否存在常规命名的{RequestDto}Response DTO。

    如果存在:

    无论服务方法的响应类型如何,都会返回 {RequestDto}Response。如果 {RequestDto}Response DTO 具有 ResponseStatus 属性,则会填充该属性,否则不会返回任何 ResponseStatus。 (如果您已使用 [DataContract]/[DataMember] 属性修饰了 {ResponseDto}Response 类和属性,则还需要修饰 ResponseStatus 以填充)。

    否则,如果没有:

    一个通用的ErrorResponse 返回一个填充的ResponseStatus 属性。

    Service Clients 透明地处理不同的错误响应类型,对于 JSON/JSV/等等无模式格式,在自定义或通用 @987654331 中返回 ResponseStatus 之间没有实际可见的区别@ - 因为它们都在线路上输出相同的响应。

    自定义异常

    最终,所有 ServiceStack WebServiceExceptions 都只是响应 DTO,带有填充的 ResponseStatus,并返回 HTTP 错误状态。有许多不同的方法可以自定义异常的返回方式,包括:

    启用 StackTraces

    默认情况下,仅在调试版本中启用在响应 DTO 中显示 StackTraces,尽管此行为可以通过以下方式覆盖:

    csharp SetConfig(new HostConfig { DebugMode = true });

    【讨论】:

    • ResponseStatus 对 C# 客户端似乎仍然有用,因为如果您返回成功消息,例如来自 RequestFilter,如果您的 DTO 定义了 ResponseStatus,您就可以读取它。我不知道使用 JsonServiceClient 的另一种方法(虽然它会很好)。
    • 我还注意到,如果您不包含 ResponseStatus,则在引发 ArgumentException 时您不会获得 HTTP 400 的默认异常行为。
    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 2014-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多