EndpointHttpContextExtensions:在.net5中找不到HttpContext类扩展(GetEn



我一直在尝试使用扩展方法GetEndpoint((,如下所述:

https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.endpointhttpcontextextensions.getendpoint?view=aspnetcore-5.0

我的项目最初是针对netstandard2.1的,但后来我在下面的帖子中读到,这个功能适用于针对netcoreapp3.1的项目。

可以';t访问.net标准中的httpcontext扩展方法

我不想以.Net Core 3.1为目标,因为我项目的实体框架核心部分使用了最新版本中提供的功能,目标是.Net Standard 2.1。

所以我试着瞄准.Net 5,看看它是否会出现,但它没有。我也尝试过安装程序包Microsoft.AspNetCore.Http.Abstractions,但没有成功(注意到这个程序包的目标是netstandard2.0(。我甚至尝试将目标框架更改为netcoreapp3.1,但没有成功。这些扩展方法根本不存在。

我错过了什么吗?或者当这些方法出现在文档中时,它们为什么在.Net 5中不可用?

如果我不能使用GetEndpoint((扩展方法,有没有其他选择?

我的目标是:我想在AuthenticationHandler:中使用以下片段

var endpoint = Context.GetEndpoint();
if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null)
return AuthenticateResult.NoResult();

编辑:

事实证明,我在.csproj文件中缺少框架参考

<FrameworkReference Include="Microsoft.AspNetCore.App" />) 

如本文所述。

然而,为了彻底回答我的问题,我还不太清楚它为我的项目提供了什么,为什么这种扩展方法不能通过正常的NuGet包使用?

我遇到了类似的问题,并使用以下包参考中的正确版本解决了问题:

<PackageReference Include="Microsoft.AspNetCore.App" Version="2.2.8" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />

最新版本的.NET将所有Microsoft程序集与SDK捆绑在一起,您的项目可以自动引用它们,而无需添加任何NuGet包。访问ASP程序集所需要做的就是将项目SDK从Microsoft.NET.Sdk更改为Microsoft.NET.Sdk.Web:

<Project Sdk="Microsoft.NET.Sdk.Web">

我也有类似的问题,你可以试试我的解决方案。

var endpoint = context.Features.Get<IEndpointFeature>()?.Endpoint;
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Microsoft.AspNetCore.Http.Features;
namespace Microsoft.AspNetCore.Http
{
/// <summary>
/// Extension methods to expose Endpoint on HttpContext.
/// </summary>
public static class EndpointHttpContextExtensions
{
/// <summary>
/// Extension method for getting the <see cref="Endpoint"/> for the current request.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> context.</param>
/// <returns>The <see cref="Endpoint"/>.</returns>
public static Endpoint? GetEndpoint(this HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
return context.Features.Get<IEndpointFeature>()?.Endpoint;
}
...

最新更新