【问题标题】:Resource leak when getting HttpContext.Current.User.Identity.Name获取 HttpContext.Current.User.Identity.Name 时的资源泄漏
【发布时间】:2015-07-18 20:55:33
【问题描述】:

我使用 HttpContext 来检索即将到来的 HTTP 请求的当前用户名,但是在运行覆盖率分析时,它报告了资源泄漏。

    public class UsersController:ApiController
    {
      private string userName;
      public UsersController()
      {
        if (HttpContext.Current != null)
        {
            userName = HttpContext.Current.User.Identity.Name;
        }
    }
    //I defined customized identity
    public class MyIdentity : IIdentity
    {
        private string name;
        public string AuthenticationType
        {
            get { return "Custom"; }
        }

        public bool IsAuthenticated
        {
            get { return true; }

        }

        public string Name { get; set; }

 }

在 Coverity 报告中,它说 2. alloc_fn:分配方法Identity.get返回一个新资源。 (虚拟调用解析为 System.Security.Claims.ClaimsPrincipal.Identity.get。) 3. noescape:资源System.Web.HttpContext.Current.User.Identity没有关闭或者保存在Name.get中。 (虚拟调用解析为 Org.Abc.HttpModules.MyIdentity.Name.get。)

CID 51307:资源泄漏 (RESOURCE_LEAK) 4.leaked_resource:System.Web.HttpContext.Current.User.Identity创建的资源保存或关闭失败会泄露。

【问题讨论】:

  • 您找到解决问题的方法了吗?
  • @AbdulAhadMonty 我直接联系了覆盖支持,他们认为这是误报,所以我的实施没有问题:)

标签: asp.net c#-4.0 asp.net-web-api memory-leaks coverity


【解决方案1】:

IIdentity 由WindowsIdentity 实现。 WindowsIdentity 还实现了 IDisposable,因此需要在创建后进行处理。您可以通过调用 Dispose 方法来执行此操作。

但是,由于您使用的是自己的 IIdentity 实现,我认为这里的问题是 Coverity 不确定该身份是否是一次性的,因此谨慎起见是错误的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多