'Owin: Exception: System.ObjectDisposedException: Cannot access a disposed object. Object name: 'System.Net.HttpListenerRequest'

I got lot of below logs like below, any one knows the root cause about this? Does this related with below code:

// Gets the client IP when hosted in IIS, where HttpContext.Current is not null.
if (httpRequest != null)
    return httpRequest.UserHostAddress;
    
// Gets the client IP when hosted in Owin, where there is no HttpContext.Current by default.
if (!request.Properties.ContainsKey("MS_OwinContext"))
    return null;
    
var context = request.Properties["MS_OwinContext"] as OwinContext;
return context?.Request.RemoteIpAddress;

Log:

Exception: System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.HttpListenerRequest'.  at System.Net.HttpListenerRequest.CheckDisposed()  at System.Net.HttpListenerRequest.get_RemoteEndPoint()  at Microsoft.Owin.Host.HttpListener.RequestProcessing.OwinHttpListenerRequest.GetRemoteIpAddress()  at Microsoft.Owin.Host.HttpListener.RequestProcessing.CallEnvironment.get_ServerRemoteIpAddress()  at Microsoft.Owin.Host.HttpListener.RequestProcessing.CallEnvironment.PropertiesTryGetValue(String key, Object& value)  at Microsoft.Owin.Host.HttpListener.RequestProcessing.CallEnvironment.TryGetValue(String key, Object& value)  at Microsoft.Owin.OwinRequest.Get[T](String key)


Solution 1:[1]

I had the similar issue earlier and found that there is a CancellationToken on Request that you can check if cancellation has been requested.

enter image description here

Below is my code where I am trying to access LocalPort of the Request (OwinRequest) and has surrounded it with if. You can use the same if.

// context.Request.LocalPort will throw ObjectDisposedException if we try to access LocalPort of cancelled
// request, thus the order of conditions in below if is important.
if (context?.Request != null &&
    !context.Request.CallCancelled.IsCancellationRequested &&
    context.Request.LocalPort != null)
{
    requestPort = context.Request.LocalPort.Value;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 abatishchev