Use HttpContext through the IHttpContextAccessor interface to get the user agent details in a Blazor Server application. The following example demonstrates how to use HttpContext to get the user agent and IP address details by default. Extend the AddHttpContextAccessor() method in the Program.cs file.
[Program.cs]
builder.Services.AddHttpContextAccessor();
[Index.razor]
@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