Press ESC to close

“IFeatureCollection has been disposed” hatası

HttpContext üzerinde işlem yaparken context’in geçersiz olması sebebiyle alınabilen hatadır. HttpContext requeste özgü ve anlık olarak yönetilen bir obje olması sebebiyle sürekli değişiklik gösterebilir. Bu sebeple bir kod bloğunun başında erişilen context ile sonunda erişilen context aynı olmayabilir.

Hatanın en yaygın sebebi IHttpContextAccessor ile HttpContext’e erişim sağlanırken Context değerinin bir property ya da field üzerine alınması ve tekrar tekrar kullanılmaya çalışılmasıdır.

Hatalı Kullanım

public class MyType
{
    private readonly HttpContext _context;
    public MyType(IHttpContextAccessor accessor)
    {
        _context = accessor.HttpContext;
    }
    
    public void CheckAdmin()
    {
        if (!_context.User.IsInRole("admin"))
        {
            throw new UnauthorizedAccessException("The current user isn't an admin");
        }
    }
}

Doğru Kullanım

public class MyType
{
    private readonly IHttpContextAccessor _accessor;
    public MyType(IHttpContextAccessor accessor)
    {
        _accessor = accessor;
    }
    
    public void CheckAdmin()
    {
        var context = _accessor.HttpContext;
        if (context != null && !context.User.IsInRole("admin"))
        {
            throw new UnauthorizedAccessException("The current user isn't an admin");
        }
    }
}

Kaynak:
https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AspNetCoreGuidance.md#do-not-store-ihttpcontextaccessorhttpcontext-in-a-field
https://stackoverflow.com/questions/59963383/session-setstring-method-throws-exception-ifeaturecollection-has-been-disposed

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir