gpt4 book ai didi

c# - 不在 asp.net core 中的 HttpRequestMessage 和 HttpResponseMessage 上调用 Dispose

转载 作者:可可西里 更新时间:2023-11-01 09:11:35 31 4
gpt4 key购买 nike

使用 asp.net core 在 HttpRequestMessage 和 HttpResponseMessage 上调用(或不调用)Dispose 的最佳实践是什么?

例子:

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());
...
}

https://github.com/aspnet/Security/blob/1.0.0/src/Microsoft.AspNetCore.Authentication.Facebook/FacebookHandler.cs#L37-L40
这两个示例都没有调用 Dispose

这会是遗漏吗?还是背后有正当理由,也许是因为该方法是异步的?当然,CG 最终会最终确定它们,但这是在这种情况下这样做的最佳做法吗?为什么?请注意,上述示例是 ASP.NET Core 中间件组件的一部分。

最佳答案

我在代码示例所属的 github 存储库上打开了一个问题。

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

It's not important in these scenarios. Disposing a request or response only calls Dispose on their Content field. Of the various HttpContent implementations, only StreamContent needs to dispose anything. HttpClient's default SendAsync fully buffers the response content and disposes the stream, so there's nothing the caller needs to do.

但是为了避免出现奇怪的错误,我们最好处理掉这些对象。 MemoryStream 是另一个类,由于其当前的底层实现,它通常也不会被处置。

https://stackoverflow.com/a/234257/6524718

If you're absolutely sure that you never want to move from a MemoryStream to another kind of stream, it's not going to do you any harm to not call Dispose. However, it's generally good practice partly because if you ever do change to use a different Stream, you don't want to get bitten by a hard-to-find bug because you chose the easy way out early on. (On the other hand, there's the YAGNI argument...)

The other reason to do it anyway is that a new implementation may introduce resources which would be freed on Dispose.

关于c# - 不在 asp.net core 中的 HttpRequestMessage 和 HttpResponseMessage 上调用 Dispose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38083206/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com