【问题标题】:ServiceStack doesn't populate the response DTO when throwing HttpErrors抛出 HttpErrors 时,ServiceStack 不会填充响应 DTO
【发布时间】:2019-05-02 12:59:56
【问题描述】:

ServiceStack 不会填充 WebServiceException 的 responseDTO 属性中的原始响应。

我正在运行下面的代码,它应该总是返回一个 404 响应代码,其中 TestResponse 的 ResponseStatus 属性填充了“一些错误的请求”,但它似乎也应该返回原始的良好响应,它的输出属性是从请求的输入属性。但是,当我查看 WebServiceException responseDTO 时,我得到了 null

        public TestResponse Post(Test request)
        {
            var response = new TestResponse() { Output = request.Input };

            throw new HttpError(response, (int)HttpStatusCode.BadRequest, "Some bad request");
        }

        public TestResponse Get(Test request)
        {
            try
            {
                using (var client = new JsonServiceClient("http://localhost:5000"))
                {
                    var response =  client.Post(request);
                    return response;
                }
            }
            catch (WebServiceException ex)
            {

                throw;
            }
        }

一般来说,我期望 WebServiceException 中的 responseDTO 属性将包含端点的 DTO,只要它在抛出 HttpError 时传入,但似乎并非如此。我只看到 responseDTO 中每个属性的默认值和空值。

【问题讨论】:

    标签: error-handling servicestack


    【解决方案1】:

    当抛出异常时,仅保留 ResponseStatus,您可以将任何其他信息添加到其 Meta 字典中。

    您也可以return a failed HTTP Response:

    public TestResponse Post(Test request)
    {
        var response = new TestResponse() { Output = request.Input };
    
        base.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return response;
    }
    

    【讨论】:

    • 我明白了。那正是我所想。在这种情况下,如果 responseDTO 的属性始终为 null/default,那么它的目的是什么?为什么 HttpError 带响应参数?
    • @NikoYakimov 响应包含 ResponseStatus,它是所有服务错误响应的错误 DTO,包含所有其他错误过滤器操作的结构化错误响应。如果你想返回额外的信息,返回错误响应,不要抛出它。
    • 太棒了。似乎这样会奏效。感谢您的快速回答!
    猜你喜欢
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    相关资源
    最近更新 更多