How do I get client IP and browser info in Blazor?

Well, I came across this issue this morning and the way I solved it for server-side Blazor was to create a class that you can then inject as a scoped service on your _host.cshtml, and then access it anywhere on your Blazor components, as Razor pages already have support for this.

    public class BlazorAppContext
    {
        /// <summary>
        /// The IP for the current session
        /// </summary>
        public string CurrentUserIP { get; set; }
    }

Startup.cs:

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
      ...

      services.AddScoped<BlazorAppContext>();

      ...
    }

_host.cshtml:

@inject IHttpContextAccessor httpContextAccessor
@{
    BlazorAppContext.CurrentUserIP =   httpContextAccessor.HttpContext.Connection?.RemoteIpAddress.ToString();
}

You can also try a Scoped approach that you can then use through DI.

Annotation:

As stated in the documentation, “Blazor WebAssembly apps don’t currently have a concept of DI scopes. Scoped-registered services behave like Singleton services. However, the Blazor Server hosting model supports the Scoped lifetime. In Blazor Server apps, a scoped service registration is scoped to the connection. For this reason, using scoped services is preferred for services that should be scoped to the current user, even if the current intent is to run the client-side in the browser.”

I hope it helps.

Leave a Comment