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");
}
}
}
-
external references and/or language specifications
ASP.NET Core Best Practices | Microsoft Learn -
type : Bug
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.