Search code examples
c#asp.net-core-webapi.net-6.0

ASP.NET Core 6 Web API: HttpContext getting null randomly. May be when API receives large number of requests


I have created an ASP.NET Core 6 Web API, using controllers. It's deployed on Azure as a web app.

It is working fine. The problem is sometime I am receiving HttpContext as null, not sure but it may occurs because of large number of requests start coming (more than 1k per second).

In my program.cs, I have:

var builder = WebApplication.CreateBuilder(args);
...
..
builder.Services.AddHttpContextAccessor();
builder.Services.AddMemoryCache();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

And in my API controller, I am using httpContext from dependency injection:

IHttpContextAccessor _httpContextAccessor;

public MyController(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

[HttpGet("MyMethod")]
public IActionResult MyMethod()
{
    var currentRequest = _httpContextAccessor.HttpContext?.Request;

    if (currentRequest == null)
    {
        throw new ArgumentNullException(nameof(currentRequest), "CurrentRequest received is NULL !");
    }
}

Ideally the httpContext should not be null in any case, but It throws error (although it happens rarely).

Am I missing some configuration? Or do I need to improve some code?


Solution

  • The problem is sometime I am receiving HttpContext as null, not sure but it may occurs because of large number of requests start coming (more than 1k per second). Am I missing some configuration? Or do I need to improve some code?

    According to your code snippet, it might be related to how ASP.NET Core handles request concurrency. When a large number of requests are being processed concurrently, there's a possibility of the HttpContext being null at certain points, especially if the request has already been completed or if it's at the early stages of processing. So, ensure that your actions/methods are marked as asynchronous (async)

    If they are performing asynchronous operations. Sometimes, synchronous code in high-concurrency scenarios can lead to race conditions.

    Therefore, yeah, you are missing async. In addition, you can directly can use context instead of using IHttpContextAccessor.

    So you can write as following:

     var currentRequest = HttpContext?.Request;
    

    According to Microsoft official docs, as its not thread-safe so out of process block it might result in null reference intermittently. As you can see below:

    enter image description here

    Note: Please refer to this official document for more information.