【问题标题】:Get user-agent and ip in Blazor server-side app在 Blazor 服务器端应用程序中获取用户代理和 ip
【发布时间】:2020-04-15 14:14:52
【问题描述】:

我使用 Blazor 创建了一个服务器端应用程序,我想在每个页面请求中获取 ipuser-agent,我该如何实现?在 .NET Core 应用程序中,我只需要在控制器中使用此代码:

var userAgent  = Request.Headers["User-Agent"].ToString()

但在 Blazor 中我无法检索此数据。

【问题讨论】:

    标签: c# .net asp.net-core blazor blazor-server-side


    【解决方案1】:

    用户代理:

    您可以通过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 cmets 和"How to use the HttpContext object in server-side Blazor to retrieve information about the user, user agent" 帖子,我意识到您可以通过第一个请求而不是通过 SignalR 请求访问HttpContext。我的意思是,Blazor 服务器通过 Http 请求将应用程序发送到客户端(浏览器),此时,当 Blazor 服务器应用程序提供给客户端时,您可以访问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();
    

    【讨论】:

    • 对于远程 IP 地址,我们可以执行以下步骤: 1- services.AddHttpContextAccessor(); 2- 在@code {} var request = httpContextAccessor.HttpContext; 3- var remoteIp = request.Connection.RemoteIpAddress
    • 试试 services.AddControllers();
    • 既然你可以得到http上下文,你也总是可以从中得到用户代理:var userAgent = httpContextAccessor.HttpContext?.Request.Headers["User-Agent"];
    猜你喜欢
    • 2022-09-29
    • 2010-12-22
    • 2021-10-29
    • 2021-03-25
    • 2020-12-18
    • 2021-05-29
    • 2021-09-21
    • 1970-01-01
    • 2020-09-18
    相关资源
    最近更新 更多