我可以为未授权或未身份验证引发的.NET 异常

当用户未经身份验证/未经授权时,我希望在代码的某些部分引发 Exception。

因此,我没有编写自己的 NotAuthenticatedException 和 NotAuthorizedException,而是想知道是否已经有一些针对这些异常的 C # 标准。

我可以想象很多程序抛出类似的异常,如果每个人都再次“编写自己的轮子”,这将不会很有用。

67622 次浏览

To avoid reinventing the wheel, I'd use PrincipalPermission.Demand or PrincipalPermissionAttribute.

A SecurityException will be thrown for you if the demand fails.

If you do want to explicitly throw an exception rather than using PrincipalPermission.Demand, you could consider reusing the existing type System.UnauthorizedAccessException, which is described in MSDN as:

The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.

It's your app rather than the OS that's denying access, but perhaps close enough.

You could also use UnauthorizedAccessException for authorization violations