SYSLIB0002:PrincipalPermissionAttribute 已過時

PrincipalPermissionAttribute 建構函式已過時,且從 .NET 5 開始產生編譯時期錯誤 SYSLIB0002。 您無法具現化此屬性,或將其套用至方法。

這與其他淘汰的警告不同,您無法隱藏錯誤。

因應措施

  • 如果您要將屬性套用至 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.
    }
    

另請參閱

PrincipalPermissionAttribute 因錯誤已過時