1

My ASP.NET Web API app needs to act as an intermediate layer between clients and another HTTP resource. The fetched response from the backend HTTP service needs to pass some basic validations - but the final response needs to be the same as from the backend call.

Here's my attempt at doing this using Web API :

[HttpGet]
public async Task<HttpResponseMessage> GetSearchResults()
{          

    var client = new HttpClient();
    var backendResponse = await client.GetAsync("http://api.duckduckgo.com/?q=DuckDuckGo&format=json");

    ValidateResponseStream(await backendResponse.Content.ReadAsStreamAsync());

    var myResponse = new HttpResponseMessage(HttpStatusCode.OK);
    myResponse.Content = backendResponse.Content;

    return myResponse;
}

While this works as intended, I think this is incorrect since I don't dispose the backendResponse.

What's a good way to dispose the backendResponse without requiring to first copy the backend response stream to a MemoryStream ?

Edit : I found this discussion thread which states explicitly that disposing a HttpResponseMessage is required; I'm still unclear whether that will happen automatically in the call above. I would also rather be explicit about Dispose being called.

2 Answers 2

1

It is always smart to dispose objects on your own. You should wrap the disposable objects in a using statement, something like this:

HttpResponseMessage myResponse;

using (var client = new HttpClient())
using(var backendResponse = await client.GetAsync("http://api.duckduckgo.com/?q=DuckDuckGo&format=json"))
{
    ValidateResponseStream(await backendResponse.Content.ReadAsStreamAsync());
    myResponse = new HttpResponseMessage(HttpStatusCode.OK);
    myResponse.Content = backendResponse.Content;
}

return myResponse;

This will ensure everything is disposed.

Also, I think you will need to make a copy if you want to dispose.

Sign up to request clarification or add additional context in comments.

Comments

0

If you already have the content you need from backendResponse, couldn't you just call backendResponse.Dispose() right before return myResponse?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.