我已经将 dotnet core 2.2 升级到 3.preview 7。
所以在那之后,我无法获得自定义属性。
context.Resource
在 2.2 版中是类型 of AuthorizationFilterContext
,但在版本 3 中是类型 of Microsoft.AspNetCore.Http.Endpoint
。
现在我无法从端点获取属性。
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace Gamma.Core.Security
{
public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute>
: AuthorizationHandler<TRequirement> where TRequirement
: IAuthorizationRequirement where TAttribute : Attribute
{
Microsoft.AspNetCore.Http.IHttpContextAccessor _httpContextAccessor = null;
public AttributeAuthorizationHandler(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
{
var attributes = new List<TAttribute>();
var action = (context.Resource as AuthorizationFilterContext)?.ActionDescriptor as ControllerActionDescriptor;
if (context.Resource is Microsoft.AspNetCore.Http.Endpoint endpoint)
{
//endpoint.
}
if (action != null)
{
attributes.AddRange(GetAttributes(action.MethodInfo));
}
return HandleRequirementAsync(context, requirement, attributes);
}
protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);
private static IEnumerable<TAttribute> GetAttributes(MemberInfo memberInfo)
{
return memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
}
}
}