我一直在尝试使用扩展方法 GetEndpoint(),详情如下:
我的项目最初是针对
netstandard2.1
但后来我在下面的帖子中读到此功能适用于针对 netcoreapp3.1
的项目。
无法访问 .net 标准中的 httpcontext 扩展方法
我不想以 .Net Core 3.1 为目标,因为我项目的 Entity Framework Core 端使用了最新版本中提供的功能,以 .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" />)
如here所述.
但是,我不太了解交付给我的项目的内容,无法彻底回答我的问题,即为什么这种扩展方法不能通过普通的 NuGet 包使用?
我有类似的问题,你可以试试我的解决方案。
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;
}
...
最新版本的 .NET 将所有 Microsoft 程序集与 SDK 捆绑在一起,您的项目会自动引用它们而无需添加任何 NuGet 包。要访问 ASP 程序集,您需要做的就是将您的项目 SDK 从
Microsoft.NET.Sdk
更改为 Microsoft.NET.Sdk.Web
:
<Project Sdk="Microsoft.NET.Sdk.Web">
我遇到了类似的问题,并通过在以下包参考中使用正确的版本来解决:
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.2.8" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />