【问题标题】:Can I get HttpStatusCode while in ServiceStack ResponseFilter?我可以在 ServiceStack ResponseFilter 中获取 HttpStatusCode 吗?
【发布时间】:2012-08-07 21:24:01
【问题描述】:

在 ResponseFilters 中是否有获取返回给客户端的状态代码(和描述)?

详细解释: 我正在考虑在响应过滤器中添加响应标头。问题是在我们的 API 中,我们设置了一些 NotFound & BadRequest 在状态描述中为用户返回一条消息;

return HttpError.NotFound(string.Format("Not found with TicketCodeId {0}",
       request.TicketCodeId))

这在各种 android 和 .net 客户端中都非常有效。 但是有些客户(我在看你的 iphone)没有得到状态描述。这个想法是在 responsefilter 中看到状态代码设置为 400 范围并且它有一个特殊的消息,然后添加一个标题并将状态消息描述复制到其中。

问题是 ResponseFilter 可以访问 IHttpResponse,并且该对象只有状态码的设置器(因此我无法确定是否需要添加标头)。

我想以这种通用方式解决它,以避免在任何设置 400 状态代码以向标头添加相同描述的地方记住(并返回所有服务实现)。如果这在一个地方完成就好了,ResponseFilter。

ResponseFilter documentation

【问题讨论】:

    标签: servicestack


    【解决方案1】:

    由于我们使用 BadRequest 和 NotFound 返回所有响应,我们在状态描述中使用消息作为 HttpError 或 HttpResult(两者都是 IHttpResult 类型),我可以执行以下操作来创建所需的额外标头:

    // Add Filter: If result is of type IHttpResult then check if the statuscode 
    // is 400 or higher and the statusdescription is set.
    this.ResponseFilters.Add((req, res, dto) =>
    {
        if (dto == null) return;
    
        var httpResult = dto as IHttpResult;
        if (dto is IHttpResult)
        {
            // If statuscode is 400 then add a Header with the error message; 
            // this since not all clients can read the statusdescription
            if ((int)httpResult.StatusCode >= 400)
                AddPmErrorMessageHeader(res, httpResult.StatusDescription);
        }
    });
    

    AddPmErrorMessageHeader 方法会做一些额外的验证并使用 res 对象来添加标题:

    res.AddHeader("PmErrorMessage", statusDescription);
    

    我对 res.OriginalResponse 进行了一些测试,但不知何故总是将 StatusCode 设置为 200,即使在设置 4** 状态代码之前也是如此。

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 2013-07-05
      • 1970-01-01
      • 2013-05-15
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多