且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Blazor服务器端应用程序中获取用户代理和IP

更新时间:2023-02-14 21:05:31

用户代理:

您可以通过JavaScript interop获取。按照以下简单步骤操作:

在您的_Host.cshtml文件上:

<script>
window.getUserAgent = () => {
    return navigator.userAgent;
};
</script>

要在任何Blazor页面上获取用户代理:

var remoteUserAgent = await JSRuntime.InvokeAsync<string>("getUserAgent");

请注意,您不需要针对每个请求发送用户代理,您可以随第一个请求一起发送它,所有其他客户端通信都将通过同一套接字进行。

远程IP:

坏消息:"目前没有好的方法。我们将研究如何向客户提供此信息。"有关详细信息,请访问How do I get client IP and browser info in Blazor?

编辑2019年12月31日:

我想我对如何访问HttpContext想得太多了。阅读一些@enet评论和"How to use the HttpContext object in server-side Blazor to retrieve information about the user, user agent"帖子,我意识到您可以通过第一个请求访问HttpContext,而不是通过SignalR请求。我的意思是,Blazor服务器通过http请求将App发送到客户端(浏览器),此时,当Blazor服务器APP被提供给客户端时,您可以访问HttpContext。我将Michael Washington的答案复制粘贴到这里(现已删除),此答案与Soroush Asadi的评论非常接近:

在启动文件中添加到ConfigureServices(IServiceCollection services)

services.AddHttpContextAccessor();

.razor页中添加:

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor

//Then call:

httpContextAccessor.HttpContext.Connection?.RemoteIpAddress.ToString();