Do not store IHttpContextAccessor.HttpContext in a field

Please follow this template to help us specify this new rule:

  • description of the Rule.
    The IHttpContextAccessor.HttpContext will return the HttpContext of the active request when accessed from the request thread. It should not be stored in a field or variable.

  • snippet of Noncompliant Code
    This example stores the HttpContext in a field then attempts to use it later.:

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");
}
}
  • snippet of Compilant Code (fixing the above noncompliant code)
    This example stores the IHttpContextAccesor itself in a field and uses the HttpContext field at the correct time (checking for null).
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");
}
}
}

Guidelines:
We want to add as many valuable rules as possible. Thus we have guidelines to help us see the value of a rule and decide if it should be implemented. Please read them before submitting your rule:

  • Is the rule useful for a developer.
    • If the rule is a Bug, Code Smell or Vulnerability it should ask the developer to fix a real problem. It shouldn’t raise warnings asking for a manual review.

I saw nobody responded to this. I assume it is about C# (.NET)?

Thank you for your suggestion, @praveenv

I have recorded it in our systems for consideration next time we look at the ASP.NET subject!

Denis

1 Like