我的应用程序使用UserPrincipal
类来确定用户所属的组,然后使用该信息来确定用户是否经过身份验证以使用我的应用程序。事情一直很好,但最近我开始得到一个例外
Guid应该包含32位数字和4个短划线(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
致电UserPrincipal.FindByIdentity
时。似乎呼叫成功并且异常正在得到妥善处理,但令我感到紧张的是,身份验证将来会突然中断。我没有在任何地方明确创建GUID,因此我不知道异常的来源。
答案 0 :(得分:6)
最有可能的是,在试图从无效的GUID值初始化某种安全描述符的Framework代码深处抛出异常。如果框架正在捕获并在内部处理它,我不会担心它。
跟踪框架代码,这里有一个可能发生的地方:
protected static bool IdentityClaimToFilter(string identity, string identityFormat, ref string filter, bool throwOnFail)
{
if (identity == null)
identity = "";
StringBuilder filter1 = new StringBuilder();
switch (identityFormat)
{
case "ms-guid":
Guid guid;
try
{
guid = new Guid(identity);
}
catch (FormatException ex)
{
if (throwOnFail)
throw new ArgumentException(ex.Message, (Exception) ex);
else
return false;
}
...
请注意,尝试创建一个新的Guid
,如果失败,则抛出异常,但代码吞下它并返回false
答案 1 :(得分:3)
如果您提供IdentityType,它将不会尝试将您的值视为Guid,因此它不会抛出异常
FindByIdentityWithType(context, typeof(UserPrincipalEx), **IdentityType.SamAccountName**, identityValue);
答案 2 :(得分:1)
我的调试系统突然开始这么做了,我无法弄清楚原因。事实证明,当我删除.user文件时,我似乎禁用了Just My Code
调试,这个异常开始被破坏。因此,检查一下这个区域周围的VS选项,你(可能)想要勾选这个:
答案 3 :(得分:-2)
只有下面的方法对我有用。
var user = _userManager.FindByNameAsync(HttpContext.User.Identity.Name);