1

在 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。

响应过滤器文档

4

1 回答 1

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** 状态代码之前也是如此。

于 2012-08-07T21:24:01.660 回答