我正在使用Visual Studio 2015来创建ASP.NET MVC 5应用程序.我正在使用Identity框架在身份验证后向用户添加声明.基于内置添加声明很容易ClaimTypes
,但我遇到了挑战,添加了一个布尔的自定义声明.
我创建了这个静态类来保存我的自定义声明类型:
public static class CustomClaimTypes
{
public static readonly string IsEmployee = "http://example.com/claims/isemployee";
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试向ClaimsIdentity
对象添加自定义声明:
userIdentity.AddClaim(new Claim(CustomClaimTypes.IsEmployee, isEmployee));
Run Code Online (Sandbox Code Playgroud)
它在上面的行中给出了这个错误:
无法转换'bool?' 到'System.Security.Claims.ClaimsIdentity'
我找到的所有例子都是添加字符串.你如何添加bool,int或其他类型?谢谢.
声明只能表示为字符串.任何数字,布尔值,指南,以及添加到索赔集合时都必须是字符串.所以ToString()
它.
userIdentity.AddClaim(
new Claim(CustomClaimTypes.IsEmployee,
isEmployee.GetValueOrDefault(false).ToString()));
Run Code Online (Sandbox Code Playgroud)
您还可以将valueType作为第三个参数传递。
userIdentity.AddClaim(
new Claim(CustomClaimTypes.IsEmployee,
isEmployee.ToString(),
ClaimValueTypes.Boolean));
Run Code Online (Sandbox Code Playgroud)
所以在前端你会得到 bool 类型的值而不是字符串。
归档时间: |
|
查看次数: |
2445 次 |
最近记录: |