C# 我可以为 Not Authorized 或 Not Authenticated 抛出的 .NET 异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15496045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.NET exceptions I can throw for Not Authorized or Not Authenticated
提问by Dirk Boer
I have parts of code where I want to throw an Exception whenever a user is not authenticated/not authorized.
我有部分代码要在用户未通过身份验证/未授权时抛出异常。
So instead of writing my own NotAuthenticatedException and NotAuthorizedException, I was wondering if there are not already some C# standards for these.
因此,我没有编写自己的 NotAuthenticatedException 和 NotAuthorizedException,而是想知道是否还没有针对这些的 C# 标准。
I can imagine a lot of programs throw similar Exceptions, and it would not be very useful if everyone 'writes their own wheel' again.
我可以想象很多程序都会抛出类似的异常,如果每个人都再次“编写自己的轮子”,那将不会很有用。
采纳答案by Darren
Use the C# AuthenticationExceptionor InvalidCredentialExceptionclass.
使用 C# AuthenticationException或InvalidCredentialException类。
http://msdn.microsoft.com/en-us/library/system.security.authentication.authenticationexception.aspx
http://msdn.microsoft.com/en-us/library/system.security.authentication.authenticationexception.aspx
回答by Joe
To avoid reinventing the wheel, I'd use PrincipalPermission.Demandor PrincipalPermissionAttribute.
为了避免重新发明轮子,我会使用PrincipalPermission.Demand或PrincipalPermissionAttribute。
A SecurityException
will be thrown for you if the demand fails.
SecurityException
如果需求失败,将为您抛出A 。
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:
如果您确实想显式抛出异常而不是使用PrincipalPermission.Demand
,则可以考虑重用现有类型System.UnauthorizedAccessException,MSDN 中将其描述为:
The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.
当操作系统因 I/O 错误或特定类型的安全错误而拒绝访问时引发的异常。
It's your app rather than the OS that's denying access, but perhaps close enough.
拒绝访问的是您的应用程序而不是操作系统,但可能已经足够接近了。
回答by Gruff Bunny
You could also use UnauthorizedAccessException for authorization violations
您还可以将UnauthorizedAccessException用于授权违规