I created a server-side app with Blazor and I want get the ip and user-agent with each page request, how can I achieve that? In a .NET Core app I just need to use this code in the controller:
var userAgent = Request.Headers["User-Agent"].ToString()
But in Blazor I can't retrieve this data.
You can use a third party API, such as Ipify, to get the IP address of the current request in Blazor. The script api. ipify will return the IP address in JSON format.
There are three possibilities for getting the user in a component (a page is a component): Inject IHttpContextAccessor and from it access HttpContext and then User ; need to register IHttpContextAccessor in Startup. ConfigureServices , normally using AddHttpContextAccessor .
With a regular Blazor application and a Standard D1 V2 instance in Azure (which has 3.5GB of memory available), the server could easily handle 5,000 concurrent users. Increase that to 14GB of memory and it could handle 20,000 concurrent users. You can find more information here.
Blazor is a web framework for building web UI components (Razor components) that can be hosted in different ways. Razor components can run server-side in ASP.NET Core (Blazor Server) versus client-side in the browser on a WebAssembly-based . NET runtime (Blazor WebAssembly, Blazor WASM).
You can get it via JavaScript interop. Follow this easy steps:
On your _Host.cshtml
file:
<script>
window.getUserAgent = () => {
return navigator.userAgent;
};
</script>
To get user agent on any Blazor page:
var remoteUserAgent = await JSRuntime.InvokeAsync<string>("getUserAgent");
Notice you don't need to send user agent on each request, you can send it with your first request, all other client-side communication will be through the same socket.
Bad news: "There is no a good way to do this at the moment. We will look into how we can provide make this information available to the client." more info at How do I get client IP and browser info in Blazor?
Edited Dec 31, 2019:
I guess I overthink about how to access to HttpContext
. Reading some @enet comments and "How to use the HttpContext object in server-side Blazor to retrieve information about the user, user agent" post, I realize that you can access HttpContext
via first request and not via SignalR requests. I mean, Blazor Server sends the App to client (browser) via Http Request, at this moment, when Blazor server app is served to client, you have access to HttpContext
. I copy-paste Michael Washington's answer here (now is removed), this answer is very closed to Soroush Asadi's comment:
In your startup file add to ConfigureServices(IServiceCollection services)
:
services.AddHttpContextAccessor();
In a .razor
page add:
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor
//Then call:
httpContextAccessor.HttpContext.Connection?.RemoteIpAddress.ToString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With