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

时间:2022-08-19 16:56:36

Using ASP.NET Web API along with ASP.NET Identity 1.0, you can use this extension method to retrieve the currently signed in user:

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

var id = Microsoft.AspNet.Identity.IdentityExtensions.GetUserId(User.Identity);

But in ASP.NET identity 2.0 alpha, you can override the type for the ID field. The example given by Microsoft shows setting this field to be an int. But this extension method seems to be hardcoded to return a string even in the alpha:

但是在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

How can you retrieve the (int) identity of the currently logged in user from within a Web API controller when using ASP.NET Identity 2.0 alpha?

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

2 个解决方案

#1


6  

You have to do the conversion manually yourself currently, because Claims are intrinsically strings. We could provide some sort of generic extension like User.Identity.GetUserId which tries to do a conversion from string -> T and this is something we are considering improving in future releases.

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

#2


6  

I ended up using :

我最终使用:

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

and calling it as : GetUserId<int>()

并将其命名为:GetUserId ()

#1


6  

You have to do the conversion manually yourself currently, because Claims are intrinsically strings. We could provide some sort of generic extension like User.Identity.GetUserId which tries to do a conversion from string -> T and this is something we are considering improving in future releases.

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

#2


6  

I ended up using :

我最终使用:

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

and calling it as : GetUserId<int>()

并将其命名为:GetUserId ()