将id类型从string更改为int时,如何在Web API中获取当前在用户中签名的id?

Ben*_*iFB 6 asp.net-mvc asp.net-web-api asp.net-identity

使用ASP.NET Web API和ASP.NET Identity 1.0,您可以使用此扩展方法来检索当前登录的用户:

var id = Microsoft.AspNet.Identity.IdentityExtensions.GetUserId(User.Identity);
Run Code Online (Sandbox Code Playgroud)

但是在ASP.NET identity 2.0 alpha中,您可以覆盖ID字段的类型.Microsoft提供的示例显示将此字段设置为int.但是这个扩展方法似乎是硬编码的,甚至在alpha中返回一个字符串:

http://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.identityextensions.getuserid(v=vs.111).aspx

在使用ASP.NET Identity 2.0 alpha时,如何从Web API控制器中检索当前登录用户的(int)标识?

Hao*_*ung 6

您必须自己手动进行转换,因为声明本质上是字符串.我们可以提供某种类型的通用扩展,例如User.Identity.GetUserId,它尝试从字符串 - > T进行转换,这是我们正在考虑在将来的版本中进行改进的内容.


Bar*_*xto 6

我最终使用:

public static class IdentityExtensions {
    public static T GetUserId<T>(this IIdentity identity) where T : IConvertible {
        return (T)Convert.ChangeType(identity.GetUserId(), typeof(T));
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其称为: GetUserId<int>()

  • 固定/添加在2.2 (5认同)