Stephen Patten
Stephen Patten

Reputation: 6363

How to get the Response Headers from IHttpResponse

I'd like to be able to retrieve the response headers for logging purposes, but do see a Headers property on the Interface, but I do see OriginalResponse. Are we supposed to cast this and use it? Will this contain any headers SS might have injected? My usage of this Interface is in a Global Filter defined as

ResponseFilters.Add((httpReq, httpResp, responseDto) =>
{
    // Log portions of the response i.e. Headers
});

Thank you, Stephen

Upvotes: 2

Views: 231

Answers (1)

mythz
mythz

Reputation: 143284

The httpReq.Headers is exactly the same instance that you would get from an ASP.NET HttpRequest.Headers or self-hosting HttpListenerRequest.Headers.

So it's exactly the same as manually casting the underlying the request and accessing it directly, e.g:

HttpRequest Headers

For ASP.NET

var aspNetRequestHeaders = ((HttpRequest)httpReq.OriginalRequest).Headers;

For HttpListener:

var httpListenerHeaders = ((HttpListenerRequest)httpReq.OriginalRequest).Headers;

HttpResponse Headers

There is no Headers collection currently exposed on the IHttpResponse so you would need to use a similar approach to access them from the underlying HTTP Response object. Though you can easily wrap them in your own Extension method, e.g:

public static NameValueCollection GetHeaders(this IHttpResponse) 
{
  var aspNetResponseHeaders = httpReq.OriginalResponse as HttpResponse;
  return aspNetResponseHeaders != null 
     ? aspNetResponseHeaders.Headers
     : ((HttpListenerResponse)httpReq.OriginalResponse).Headers; //Http Listener
}

Upvotes: 3

Related Questions