简体   繁体   中英

How do I Dispose a HttpResponseMessage in my Web Api Method?

I'm getting the CA2000 error on all my Wep Api 2 controllers for the Options() verb.

In method 'PromotionController.Options()', object '<>g__initLocal0' is not disposed along all exception paths.

I need to support pre-flight requests made for cross domain ajax calls so all I'm doing is returning a HttpStatusCode.Ok so that the subsequent post/put/delete will fire off.

public HttpResponseMessage Options()
{
    return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}

I have tried the using statement like this:

public HttpResponseMessage Options()
{
    using(var response = new HttpResponseMessage())
    {
        response.StatusCode = HttpStatusCode.OK;
        return response;
    }
}

but when I hit it with an Options request from Postman I get an exception:

Cannot access a disposed object.\\r\\nObject name: 'System.Net.Http.HttpResponseMessage'.

How do I return the HttpStatusCode.Ok in a way that it won't throw Code Analysis errors?

Thanks!

Exception about accessing a disposed object is obvious because when execution leaves the using block, response is disposed, but you're returning it out of the using block and out of the method. You can't access that object outside of the method, because it simply doesn't exist anymore.

In general, to solve the CA2000 warning simply dispose the instance of HttpResponseMessage class explicitly when you don't need it anymore.

In your case solution could be to override the Dispose method of your controller (implements the ApiController method) and explicitly dispose your instances there . Check for example this question .

You can also just suppress the warning and instance will be disposed later by the garbage collector anyway. But it's not a proper solution.

You can register the response object for disposing using RegisterForDispose method of HttpRequestMessage class. Infrastructure of .Net will disposes all registered object after disposing the request.

I can't guaranty that you won't get the error after that, but the object will be disposed so that you can suppress the error.

Example :

HttpResponseMessage response = Request.CreateResponse();
// Do what you need with response
// ...
// ...
request.RegisterForDispose(response);// response will be disposed by host

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM