簡體   English   中英

如何正確處理從 controller 返回的 HttpResponseMessage?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM