如何在服务器端 Blazor 中使用 HttpContext 对象来检索有关用户、用户代理的信息

Isa*_*aac 14 blazor blazor-server-side

IP 地址等。通常,当用户询问如何在 Server Blazor 应用程序中执行此操作时,他们要么被告知这是不可能的,要么有时会提供使用 JSInterop 的部分解决方案。但是可以在不诉诸 JSInterop 的情况下完成吗?这是答案...

Isa*_*aac 36

该小说HttpContext对象无法与Blazor服务器应用程序可以使用,已经长繁殖#1,它是高的时候养老金其关闭。

确实,HttpContext当 WebSocket 连接在运行时不可用,但必须明确:当您键入 url 并按 Enter 按钮时,与服务器端 Blazor 应用程序的连接是 HTTP 连接,而不是WebSocket 连接。

因此,您的应用程序可以HttpContext像在 Razor Pages 应用程序或 MVC 应用程序中一样访问和使用它,包括获取用户代理和 IP 地址。以下代码示例演示了如何使用HttpContext本地获取用户代理和 IP 地址,而不使用JSInterop应作为最后手段使用的,并将提取的值传递给App组件。

  1. 将文件添加到文件Pages夹中并将其命名为_Host.cshtml.cs.
  2. 将此代码添加到文件中:
public class HostModel: PageModel
{
    private readonly IHttpContextAccessor _httpContextAccssor;
    
    public HttpContextFeatureModel(IHttpContextAccessor httpContextAccssor)
    {
        _httpContextAccssor = httpContextAccssor;    
    }

    public string UserAgent { get; set; }
    public string IPAddress { get; set; }
    
    // The following links may be useful for getting the IP Adress:
    // https://stackoverflow.com/questions/35441521/remoteipaddress-is-always-null
    // https://stackoverflow.com/questions/28664686/how-do-i-get-client-ip-address-in-asp-net-core
    
    public void OnGet()
    {
        UserAgent = _httpContextAccssor.HttpContext.Request.Headers["User-Agent"];
        // Note that the RemoteIpAddress property returns an IPAdrress object 
        // which you can query to get required information. Here, however, we pass 
        // its string representation
        IPAddress = _httpContextAccssor.HttpContext.Connection.RemoteIpAddress.ToString();  
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能需要以下一种或多种用途:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
Run Code Online (Sandbox Code Playgroud)
  1. Host.cshthml将以下行添加到您的页面(在靠近 using 和那些东西的页面顶部):
@model HostModel
Run Code Online (Sandbox Code Playgroud)
  1. App组件中,定义两个参数属性,这些属性将获取并存储从位于 中的组件标记传递给它的用户代理和 IP 地址_Host.cshtml

App.razor:

<p>UserAgent: @UserAgent</p>
<p>IPAddress: @IPAddress</p>

@code
{
    [Parameter]
    public string UserAgent { get; set; }

    [Parameter]
    public string IPAddress { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
  1. _Host.cshtml更新组件标签这样的(这个方法现在已经过时了):
<app>
    <component type="typeof(App)" render-mode="ServerPrerendered" param-UserAgent="@Model.UserAgent" param-IPAddress="@Model.IPAddress" />
</app>
Run Code Online (Sandbox Code Playgroud)

在当前的 Blazor 服务器端应用程序中,可以这样做:

<div>
    @(await Html.RenderComponentAsync<App>(RenderMode.Server, new { IPAddress = Model.IPAddress, UserAgent = Model.UserAgent }))
</div>
Run Code Online (Sandbox Code Playgroud)
  1. 添加services.AddHttpContextAccessor();toStartupConfigureServices方法以启用对 HttpContext 的访问。

就这些。您也可以将 添加Identity UI到您的 Blazor 服务器应用程序,并应用上面显示的相同过程从 中提取声明主体HttpContext,在用户通过身份验证后(这样做仅用于学习目的,因为您应该使用 AuthenticationStateProvider)。

这也是有关当前主题的官方文档的链接

  • 如果没有 HttpContextAccessor 我也可以完成:https://github.com/aspnet/AspNetCore/issues/18070#issuecomment-570295377 (3认同)
  • 请参阅上面我的第一条评论,其中我说不需要 HttpContextAccessor,因为您可以直接访问作为 ModelPage 对象的属性提供的 HttpContext (3认同)
  • .NET 团队本身似乎拒绝任何使用“HttpContext”的解决方法,例如这个。对 @enet 有什么想法吗?文档通常很可怕。相关问题:https://github.com/dotnet/aspnetcore/issues/34095 (3认同)
  • 是否有一个 .net core 版本可以让您的指令进行编译? (2认同)
  • 感谢您的帖子,@enet。没有提到的是如何从任何页面访问IP地址。我找到了一种方法 - 在 App.razor 中添加一个级联值,如下所示: &lt;CascadingValue Name="IPAddress" Value="@IPAddress"&gt;。然后从任何页面执行以下操作: [CascadingParameter(Name = "IPAddress")] public string IPAddress { get; 放; }。就是这样!希望这对其他人有帮助。 (2认同)
  • “.NET 团队本身似乎拒绝任何使用‘HttpContext’的解决方法,比如这个。” 这是毫无根据的虚假陈述。这不是解决方法。这就是编码的方式。我是第一个公开展示如何正确使用 HttpContext 的人。我在这里展示的内容出现在一年多后的文档中(https://learn.microsoft.com/en-us/aspnet/core/blazor/security/server/additional-scenarios?view=aspnetcore-6.0#pass-tokens -到-blazor-服务器应用程序)。在我看来,你并没有完全理解这个问题和解决方案。 (2认同)

归档时间:

查看次数:

9328 次

最近记录:

4 年,5 月 前