首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异常: System.ObjectDisposedException:无法访问已释放的对象。对象名称:“System.Net.HttpListenerRequest”

异常: System.ObjectDisposedException:无法访问已释放的对象。对象名称:“System.Net.HttpListenerRequest”
EN

Stack Overflow用户
提问于 2018-07-25 06:10:52
回答 1查看 932关注 0票数 4

我有很多像下面这样的日志,有人知道这个的根本原因吗?这是否与以下代码相关:

代码语言:javascript
复制
// 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;

日志:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2022-02-16 17:15:49

我之前也有过类似的问题,发现Request上有一个Request,您可以检查是否有人请求取消。

下面是我的代码,在这里我试图访问LocalPort of Request (OwinRequest),并将其包围在if中。您可以使用相同的if

代码语言:javascript
复制
// 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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51511932

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档