在 Blazor 服务器端应用程序中获取用户代理和 ip
Get user-agent and ip in Blazor server-side app
我用 Blazor 创建了一个服务器端应用程序,我想在每个页面请求中获取 ip 和 user-agent,如何我能做到吗?在 .NET Core 应用程序中,我只需要在控制器中使用此代码:
var userAgent = Request.Headers["User-Agent"].ToString()
但在 Blazor 中我无法检索此数据。
用户代理:
您可以通过JavaScript interop获取。按照这个简单的步骤操作:
在您的 _Host.cshtml
文件中:
<script>
window.getUserAgent = () => {
return navigator.userAgent;
};
</script>
要在任何 Blazor 页面上获取用户代理:
var remoteUserAgent = await JSRuntime.InvokeAsync<string>("getUserAgent");
请注意,您不需要在每个请求上都发送用户代理,您可以在第一个请求中发送它,所有其他客户端通信都将通过同一个套接字。
远程IP:
坏消息:"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." 更多信息请访问
已编辑 2019 年 12 月 31 日:
我想我想多了如何访问 HttpContext
。正在阅读一些 @enet comments and 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 的评论:
在您的启动文件中添加 ConfigureServices(IServiceCollection services)
:
services.AddHttpContextAccessor();
在 .razor
页面添加:
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor
//Then call:
httpContextAccessor.HttpContext.Connection?.RemoteIpAddress.ToString();
我用 Blazor 创建了一个服务器端应用程序,我想在每个页面请求中获取 ip 和 user-agent,如何我能做到吗?在 .NET Core 应用程序中,我只需要在控制器中使用此代码:
var userAgent = Request.Headers["User-Agent"].ToString()
但在 Blazor 中我无法检索此数据。
用户代理:
您可以通过JavaScript interop获取。按照这个简单的步骤操作:
在您的 _Host.cshtml
文件中:
<script>
window.getUserAgent = () => {
return navigator.userAgent;
};
</script>
要在任何 Blazor 页面上获取用户代理:
var remoteUserAgent = await JSRuntime.InvokeAsync<string>("getUserAgent");
请注意,您不需要在每个请求上都发送用户代理,您可以在第一个请求中发送它,所有其他客户端通信都将通过同一个套接字。
远程IP:
坏消息:"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." 更多信息请访问
已编辑 2019 年 12 月 31 日:
我想我想多了如何访问 HttpContext
。正在阅读一些 @enet comments and 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 的评论:
在您的启动文件中添加 ConfigureServices(IServiceCollection services)
:
services.AddHttpContextAccessor();
在 .razor
页面添加:
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor
//Then call:
httpContextAccessor.HttpContext.Connection?.RemoteIpAddress.ToString();