Do not call Dispose on HttpRequestMessage and HttpResponseMessage in asp.net core

What is the best practice for calling Dispose (or not) in HttpRequestMessage and HttpResponseMessage with asp.net core?

Examples:

https://github.com/aspnet/Security/blob/1.0.0/src/Microsoft.AspNetCore.Authentication.Google/GoogleHandler.cs#L28-L34

protected override async Task<AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) { // Get the Google user var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); var response = await Backchannel.SendAsync(request, Context.RequestAborted); response.EnsureSuccessStatusCode(); var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); ... } 

and https://github.com/aspnet/Security/blob/1.0.0/src/Microsoft.AspNetCore.Authentication.Facebook/FacebookHandler.cs#L37-L40
Both examples do not call Dispose

Could this be an omission? or is there a good reason, maybe because the isync method?

Edit 1: of course, CG will eventually refine them, but is it better to do this in this case and why?

Edit 2: the above examples are part of asp.net middleware middleware

+6
source share
1 answer

I discovered the problem in the github repository, which contains code examples.

https://github.com/aspnet/Security/issues/886

This is not important in these scenarios. Removing a request or response only causes Dispose calls in their Content field. Of the various implementations of HttpContent, only StreamContent should handle anything. By default, HttpClient SendAsync fully buffers the contents of the response and provides a stream, so the caller does not need to do anything.

But in order to not get strange errors along the line, we better get rid of this object. MemoryStream is another class that is also often not disposed of due to its current base implementation.

fooobar.com/questions/26839 / ...

If you are absolutely sure that you never want to switch from MemoryStream to another stream, you will not do any harm not to cause Dispose. However, this is usually a good practice, in part because if you ever make changes to use another thread, you do not want to be bitten by an inaccessible bug, because you chose an easy way out at an early stage. (On the other hand, there is an argument of YAGNI ...)

Another reason to do this anyway is that the new implementation may introduce resources that will be released in Dispose.

+4
source

All Articles