我有一个Asp.Net Core 2.2应用程序。当我迁移到Asp.Net Core 3.0时,出现以下错误:
引用“ IAuthorizeData”类型声明其定义于 'Microsoft.AspNetCore.Authorization',但找不到
我正在使用TagHelperSamples.Authorization
nuget包根据用户权限和角色来选择呈现HTML的一部分。
如果用户获得了如下所示的授权,我正在使用上述nuget软件包中的asp-authorize
标签帮助程序来显示菜单:
<div asp-authorize class="collapse navbar-collapse" id="navbarCollapse">
这些标签帮助程序在构建项目时产生错误。
我尝试在@using Microsoft.AspNetCore.Authorization
中添加_ViewImports.cshtml
,但这不起作用。
是否有任何有关解决此问题或任何变通办法的帮助/建议?
答案 0 :(得分:0)
TagHelperSamples.Authorization
尚不适合asp.net core 3.0,请参阅
https://github.com/dpaquette/TagHelperSamples/issues/77
您可以只删除该包,并在asp.net core 3.0项目中基于source code手动创建您的授权标签帮助程序类:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Asp3identityCore.TagHelpers
{
[HtmlTargetElement(Attributes = "asp-authorize")]
[HtmlTargetElement(Attributes = "asp-authorize,asp-policy")]
[HtmlTargetElement(Attributes = "asp-authorize,asp-roles")]
[HtmlTargetElement(Attributes = "asp-authorize,asp-authentication-schemes")]
public class AuthorizationPolicyTagHelper : TagHelper, IAuthorizeData
{
private readonly IAuthorizationPolicyProvider _policyProvider;
private readonly IPolicyEvaluator _policyEvaluator;
private readonly IHttpContextAccessor _httpContextAccessor;
public AuthorizationPolicyTagHelper(IHttpContextAccessor httpContextAccessor, IAuthorizationPolicyProvider policyProvider, IPolicyEvaluator policyEvaluator)
{
_httpContextAccessor = httpContextAccessor;
_policyProvider = policyProvider;
_policyEvaluator = policyEvaluator;
}
/// <summary>
/// Gets or sets the policy name that determines access to the HTML block.
/// </summary>
[HtmlAttributeName("asp-policy")]
public string Policy { get; set; }
/// <summary>
/// Gets or sets a comma delimited list of roles that are allowed to access the HTML block.
/// </summary>
[HtmlAttributeName("asp-roles")]
public string Roles { get; set; }
/// <summary>
/// Gets or sets a comma delimited list of schemes from which user information is constructed.
/// </summary>
[HtmlAttributeName("asp-authentication-schemes")]
public string AuthenticationSchemes { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var policy = await AuthorizationPolicy.CombineAsync(_policyProvider, new[] { this });
var authenticateResult = await _policyEvaluator.AuthenticateAsync(policy, _httpContextAccessor.HttpContext);
var authorizeResult = await _policyEvaluator.AuthorizeAsync(policy, authenticateResult, _httpContextAccessor.HttpContext, null);
if (!authorizeResult.Succeeded)
{
output.SuppressOutput();
}
}
}
}
答案 1 :(得分:0)
我已经更新了TagHelperSamples.Authorization程序包以支持ASP.NET Core 3.0。升级到最新的软件包版本将解决您的问题:https://www.nuget.org/packages/TagHelperSamples.Authorization/