最近在搭建公司私服,将一些项目中常用的中间件统一封装后提供Nuget包对外使用,使用的版本是.NET Standard 2.0
其中有一个中间件中获取特性标签的关键代码如下var permissionFilters = endpoint?.Metadata?.GetOrderedMetadata<PermissionAttribute>();
中间件部分代码如下:
/// <summary>
/// 权限验证中间件
/// </summary>
public class AuthMiddleware
{
/// <summary>
/// Initializes a new instance of the <see cref="AuthMiddleware"/> class.
/// </summary>
/// <param name="next"></param>
public AuthMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary>
/// 权限请求
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task Invoke(HttpContext context)
{
var endpoint = context.Features.Get<IEndpointFeature>()?.Endpoint;
// 无需登陆验证
var attribute = endpoint?.Metadata.GetMetadata<NoLoginFilterAttribute>();
// 无需校验EJWT标识
var noEJWTAttribute = endpoint?.Metadata?.GetMetadata<NoEJWTAttribute>();
var permissionFilters = endpoint?.Metadata?.GetOrderedMetadata<PermissionAttribute>();
await _next.Invoke(context);
}
该代码
在dotnetcore webapi 3.1中使用的程序集是
在.NET Standard2.0中官方只提供的程序集是
单元测试时在dotnetcore webapi3.1项目中添加引用后启动出现如下错误:
问题错误:
异常信息:
An unhandled exception occurred while processing the request.
MissingMethodException: Method not found: 'System.Collections.Generic.IEnumerable`1<!!0> Microsoft.AspNetCore.Http.EndpointMetadataCollection.GetOrderedMetadata()'.
eHospital.Core.Middlerware.AuthMiddleware.AuthMiddleware.Invoke(HttpContext context)
System.MissingMethodException: Method not found: 'System.Collections.Generic.IEnumerable`1<!!0> Microsoft.AspNetCore.Http.EndpointMetadataCollection.GetOrderedMetadata()'.
at eHospital.Core.Middlerware.AuthMiddleware.AuthMiddleware.Invoke(HttpContext context)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at eHospital.Core.Middlerware.AuthMiddleware.AuthMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
于是注释掉提示的错误代码:
项目可正常运行:
逐步调试,该方法能正常获取:
控制器方法定义:
中间件Invoke方法:
不知道博客园大神门有没有遇到过 初步怀疑是版本的问题,可是在将目标框架从.NET standard 2.0 改为 .NET Core 3.1(长期支持)后也是相同的问题。