1
votes

While in the ResponseFilters is there anyway to get the status code (and description) which is going back to the client?

Long explanation: I'm looking into adding a response header while I'm in a response filter. The issue is that in our API we set on some NotFound & BadRequest returns a message for the user in the status description;

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

This works great in android and .net clients of all sorts. But some clients (I'm looking at you iphone) don't get the status description. The idea is to see in the responsefilter that the status code is set to 400 range and it has a special message, then add a header and copy the status message description into it.

Problem is ResponseFilter has access to IHttpResponse, and that object has only a setter to the statuscode (so no way for me to determine if I need to add the header).

I want to solve it in this generic way to avoid having to remember (and go back over all service implementations) everywhere a 400 status code is set to add the same description to a header. It would be nice if this is done in a single place, the ResponseFilter.

ResponseFilter documentation

1

1 Answers

1
votes

Since we are returning all responses with BadRequest and NotFound where we use a message in the status description as either an HttpError or HttpResult (which both are of type IHttpResult) I can do the following to create the desired extra header:

// 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);
    }
});

The AddPmErrorMessageHeader method will do some extra validation and use the res object to add the header:

res.AddHeader("PmErrorMessage", statusDescription);

I did some testing with the res.OriginalResponse but that somehow always has the StatusCode set to 200, even when just before setting the 4** status code.