如何在服务器端Blazor中使用HttpContext对象检索有关用户,用户代理的信息 [英] How to use the HttpContext object in server-side Blazor to retrieve information about the user, user agent
问题描述
IP地址,等等.很多时候,当用户询问如何在Server Blazor应用程序中执行此操作时,他们要么被告知不可能,要么有时会提供使用JSInterop的部分解决方案.但是可以不借助JSInterop来完成吗?这就是答案...
IP Address, and such like. Very often when users ask how to do it in Server Blazor app, they are either told that it is not possible, or sometimes offered partial solutions employing JSInterop. But can it be done without resorting to JSInterop ? Here's the answer...
推荐答案
关于HttpContext
对象不能与Blazor Server App一起使用的说法已经在Stackoverflow上广泛传播,现在是时候对其进行退休了关闭.
The fiction that the HttpContext
object can't be used with Blazor Server App, has been long propagated on Stackoverflow, and it is high time to pension it off.
的确,当WebSocket连接正在运行时,HttpContext
不可用,但是必须清除:在键入URL并按Enter键时,与服务器端Blazor应用程序的连接是HTTP连接,而不是WebSocket连接.
It is true that the HttpContext
is not available when a WebSocket connection is in operation, but this must be clear: When you type an url and press the enter button, the connection to your server-side Blazor app is an HTTP connection, and not a WebSocket connection.
因此,您的应用程序可以以与Razor Pages应用程序或MVC应用程序相同的方式访问和使用HttpContext
,包括获取用户代理和IP地址.下面的代码示例演示如何使用HttpContext
本机获取用户代理和IP地址,而无需使用应作为最后手段的JSInterop
并将提取的值传递给App
组件.>
Thus, your app can access and use the HttpContext
in the same way it is used in a Razor Pages App or a MVC App, including getting the User Agent and an IP Address. The following code sample demonstrates how to use the HttpContext
to get the User Agent and IP Address natively, without using JSInterop
which should be used as a last resort, and pass the extracted values to the App
component.
- 将文件添加到
Pages
文件夹并将其命名为_Host.cshtml.cs
. - 将此代码添加到文件中:
- Add a file to the
Pages
folder and name it_Host.cshtml.cs
. - Add this code to the file:
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();
}
}
您可能需要以下一种或多种用途:
You may need one or more of these usings:
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;
- 将以下行添加到您的
Host.cshthml
页中(在页面顶部,靠近用法和相关内容):
- Add the following line to your
Host.cshthml
page (on top of the page near to the usings and that stuff):
@model HostModel
- 在
App
组件中,定义两个参数属性,这些属性将获取并存储从位于_Host.cshtml
的组件标签传递给它的用户代理和IP地址.
- In the
App
component, define two parameter properties which will get and store the User Agent and IP Address passed to it from the component tag located in_Host.cshtml
.
App.razor:
App.razor:
<p>UserAgent: @UserAgent</p>
<p>IPAddress: @IPAddress</p>
@code
{
[Parameter]
public string UserAgent { get; set; }
[Parameter]
public string IPAddress { get; set; }
}
- 在
_Host.cshtml
中像这样更新组件标签(此方法现在已过时):
- In
_Host.cshtml
update the component tag like this (This method is outdated now):
<app>
<component type="typeof(App)" render-mode="ServerPrerendered" param-UserAgent="@Model.UserAgent" param-IPAddress="@Model.IPAddress" />
</app>
在当前的Blazor服务器端应用程序中,可以这样做:
In current Blazor server side apps, this can be done like this:
<div>
@(await Html.RenderComponentAsync<App>(RenderMode.Server, new { IPAddress = Model.IPAddress, UserAgent = Model.UserAgent }))
</div>
- 在
Startup
的ConfigureServices
方法中添加services.AddHttpContextAccessor();
以启用对HttpContext的访问.
- Add
services.AddHttpContextAccessor();
toStartup
'sConfigureServices
method to enable access to the HttpContext.
仅此而已.您还可以将Identity UI
添加到您的Blazor Server应用程序中,并应用上述所示的相同步骤从用户验证后的HttpContext
中提取索赔主体(这样做仅出于学习目的,因为您应该使用而是使用AuthenticationStateProvider).
That is all. You can add the Identity UI
to your Blazor Server App as well and apply the same procedure shown above to extract the claims principal from the HttpContext
, after the user has authenticated (do that for learning purpose only, as you should use the AuthenticationStateProvider instead).
这也是我的问题的链接我刚刚回答了有关在Blazor Server应用中设置同意cookie的问题.
Here's also a link to a question I've just answered about setting the consent cookie in a Blazor Server App.
这篇关于如何在服务器端Blazor中使用HttpContext对象检索有关用户,用户代理的信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!