[英]How to properly dispose HttpResponseMessage returned from a controller?
我有一个返回HttpResponseMessage
的操作。
我该如何处置这样的 object? 退回后,我真的无法处理它。
例子:
return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
// Inside function SomeMethod
我的行动:
public HttpResponseMessage SomeAction()
{
return SomeMethod(); // Warning that this is not disposed
}
这很奇怪,因为在我的代码的其他部分不存在这样的警告。 function 是否让我的IntelliSense
感到困惑?
该操作不会从其他任何地方调用。
它将结果返回到其端点。
经过研究,根据本文的最佳做法是处置它。
它指出:
最安全、最通用的建议是在使用完 HttpResponseMessage 后始终将其丢弃。 这确实会导致更多的代码噪音,但可以确保无论内部结构和未来的任何更改如何,您的代码都会尽快释放/清理未使用的资源,例如连接。 请注意,一旦您处理了该内容,它将变得无法被其他任何通过引用它的人使用。
本文提供了这个示例,说明如何正确使用 HttpResponseMessage 然后将其处理掉
public async Task<SomeData> GetSomeDataAsync(Uri uri)
{
HttpResponseMessage response = await _httpClient.GetAsync(uri);
SomeData result = null;
try
{
// In this case we'll expect our caller to handle a HttpRequestException
// if this request was not successful.
response.EnsureSuccessStatusCode();
result = await response.Content?.ReadAsAsync<SomeData>();
}
finally
{
// Dispose of HttpResponseMessage to ensure we free up system resources
// and release the network connection (if that hasn't already happened).
// Not required in a majority of common cases but always safe to do as long
// as you have not passed the content onto other threads / consumers.
response.Dispose();
}
// Either return the result or in this case a daft
// default value. It's okay for this example!
return result ?? SomeData.Empty;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.