1

The problem

I'm running into an issue where I cannot access HttpContext in @code placed within a razor component because it is null whenever the client is an iOS mobile device(tested on Safari and Firefox with iOS and iPadOS. Also tested on a Pixel 2 using Chrome, and the issue was non-existent). I know this is limited to mobile iOS devices because, from a desktop browser (tested with Firefox|Chromium on Ubuntu, and Firefox|Safari on macOS), HttpContext is an object containing all of the expected attributes.

Example

TheComponent.razor

@inject IHttpContextAccessor _httpContext

@*html and other components that ultimately call the function below*@

@code
{
    private void SomeFuncCalledByAButton(){
    
        Console.WriteLine(_httpContext.ToString());
        //"Microsoft.AspNetCore.Http.HttpContextAccessor"

        if(_httpContext.HttpContext is null){
            // This block is ALWAYS entered when an iOS device visits the page and clicks the button
            Console.WriteLine("It's null!"); //It's null!
            Console.WriteLine(_httpContext.HttpContext.ToString());//Raises System.NullReferenceException
        }else{
            //This block is ALWAYS entered when DESKTOP devices access the page and click the button
            Console.WriteLine(_httpContext.HttpContext.ToString());//Microsoft.AspNetCore.Http.DefaultHttpContext
        }
    }

}

tl;dr

HttpContextAccessor's HttpContext is null when the razor component is accessed from an iOS device, but is a normal object when the component is accessed from a desktop device.

How can I go about getting the HttpContext when any browser accesses my razor component?

Joshua Schlichting
  • 3,110
  • 6
  • 28
  • 54
  • Does https://github.com/dotnet/aspnetcore/issues/5144 explain what you are seeing? – mjwills Oct 07 '20 at 04:39
  • What version of .NET Core are you running? – mjwills Oct 07 '20 at 04:39
  • @mjwills .NET Core 3.1 - The linked github issue is very similar to what I'm seeing, but my issue is specifically that it's only `null` when my iOS device loads the page via Safari or Firefox for iOS (Those are the only two I've tested). Any desktop accessing the page works fine, my program can pull data out of `HttpContext` when it's a desktop user visiting the site. – Joshua Schlichting Oct 07 '20 at 14:46
  • 1
    Please read this https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-3.1#blazor-and-shared-state - then rethink what you are trying to achieve with HttpContext - and how you can do that differently in Blazor. – Mister Magoo Oct 13 '20 at 23:13
  • @JoshuaSchlichting. Any news in the topic, how you solved it? I am facing the same problem in my Blazor Server App. I have tried with IHttpContextAccessor in my components but it fails pretty often on iOS-devices. It works perfectly on all other. – Henrik Bengtsson Nov 30 '21 at 12:08

0 Answers0