Live Chat Icon For mobile
Live Chat Icon

How do you use the HttpContext object in Blazor server-side to retrieve information about the user or user agent?

Platform: Blazor| Category : Tips and Tricks, General

Use HttpContext through the IHttpContextAccessor interface to get the user agent details in a Blazor Server application. The following example demonstrates how to use HttpContent to get the user agent and IP address details by default.
Extend the AddHttpContextAccessor() configuration to the ConfigureServices method in the Startup.cs file.


public void ConfigureServices(IServiceCollection services)
    // . . .


@page "/"
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor

<p>UserAgent = @UserAgent</p>
<p>IPAddress = @IPAddress</p>

@code {
    public string UserAgent { get; set; }
    public string IPAddress { get; set; }

    protected override void OnInitialized()
        UserAgent = httpContextAccessor.HttpContext.Request.Headers["User-Agent"];
        IPAddress = httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

Refer to this link for more details.

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.