Does User.Identity.Name ever throw?
-
01-07-2021 - |
質問
I notice User.Identity.Name
appears to return the empty string when there is no user authenticated, rather than throwing a null reference exception.
It is valid to assume User.Identity.Name
will never throw? Or should I be checking for null Identity
before access.
解決
I believe that the User object can be null if you haven't called
FormsAuthentication.SetAuthCookie(UserName, False)
or
FormsAuthentication.RedirectFromLoginPage(UserName, False)
It would probably be best to wrap in a try catch.
他のヒント
User.Identity
will throw a null reference exception if there is no User
in the current HttpContext
. Though it is User
that is null, not Identity
. So yes, you should check or handle the null in some way.
While Name
is a string, Identity
and User
are objects, that certainly can be null as any object can.
Hence, there always a chance for exception to be thrown and as a production application you better wrap it by try/catch as well as check the Name for null.
Name
is a property as opposed to a method, so the "getter" bit of it is highly unlikely to throw an exception, as it's a Microsoft class, and their framework design guidelines explicitly warn against throwing exceptions from getters. Although there's probably an exception to this rule somewhere...
Also, I generally use the metadata as a guide to what, if any exceptions are thrown by a method (for .Net framework classes). Hitting F12 in Visual Studio (if you haven't got Reflector or something similar installed) will show you the metadata. In the comments block above the method, it generally gives you the exact types of exceptions that the method may throw.