构造 PrincipalPermissionAttribute 函数已过时,并生成编译时错误。 不能实例化此属性或将其应用于方法。
更改描述
在 .NET Framework 和 .NET Core 上,可以使用特性批注方法 PrincipalPermissionAttribute 。 例如:
[PrincipalPermission(SecurityAction.Demand, Role = "Administrators")]
public void MyMethod()
{
// Code that should only run when the current user is an administrator.
}
从 .NET 5 开始,不能将 PrincipalPermissionAttribute 属性应用于方法。 特性的构造函数已过时,并生成编译时错误。 与其他过时警告不同,无法禁止显示错误。
更改原因
与子类的其他类型一样,该 PrincipalPermissionAttribute 类型是子类 SecurityAttribute的一部分。NET 的代码访问安全性(CAS)基础结构。 在 .NET Framework 2.x - 4.x 中,即使应用程序在完全信任环境下运行,运行时仍然会对方法入口强制应用 PrincipalPermissionAttribute 注释。 .NET Core 和 .NET 5 及更高版本不支持 CAS 属性,运行时将忽略它们。
从 .NET Framework 到 .NET Core 和 .NET 5 的行为差异可能导致“无法打开”的情况,在这种情况下,本应阻止但却允许了访问。 若要防止“打开失败”情况,不能再在面向.NET 5或更高版本的代码中应用该属性。
已引入的版本
5.0
建议的操作
如果遇到过时错误,则必须采取措施。
如果要将特性应用于 ASP.NET MVC 操作方法:
请考虑使用 ASP。NET 的内置授权基础结构。 以下代码演示如何使用 AuthorizeAttribute 属性批注控制器。 在执行作之前,ASP.NET 运行时将授权用户。
using Microsoft.AspNetCore.Authorization; namespace MySampleApp { [Authorize(Roles = "Administrator")] public class AdministrationController : Controller { public ActionResult MyAction() { // This code won't run unless the current user // is in the 'Administrator' role. } } }
有关详细信息,请参阅 ASP.NET Core 中的基于角色的授权 ,以及 ASP.NET Core 中的授权简介。
如果要将属性应用于 Web 应用上下文之外的库代码:
在方法开始时手动执行检查。 通过使用IPrincipal.IsInRole(String)方法可以实现这一点。
using System.Threading; void DoSomething() { if (Thread.CurrentPrincipal == null || !Thread.CurrentPrincipal.IsInRole("Administrators")) { throw new Exception("User is anonymous or isn't an admin."); } // Code that should run only when user is an administrator. }