문제

I'm using the new WIF 4.5 SDK, but i have the same annoying exception that with LINQ is resolved with .FirstorDefault()

 var claimEmail = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;

The problem here is that Windows Live ID have no email value in the claim, so if an user log in with a live ID i have a NullReferenceException - Object reference not set to an instance of an object. I also tried;

var claimEmail = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value.FirstorDefault();

without success

How can i return NULL or "" if ther's no email in the claim?

Thanks

도움이 되었습니까?

해결책

There isn't a FirstOrDefault shortcut in the ClaimsPrincipal class, but you can always just use LINQ to iterate the list of claims to do the same thing:

var claimEmail = ClaimsPrincipal.Current.Claims.Where(c => c.Type == ClaimTypes.Email).FirstOrDefault();

Or you can just put in a check to make sure the Claim isn't NULL:

var claimEmail = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email);
var email = (claimEmail == null ? string.Empty : claimEmail.Value);

Hopefully this helps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top