ASP.Net MVC에서 User 개체의 UserID를 어떻게 얻습니까?
aspnet_Users.UserID와 관련된 고유 식별자 UserID가있는 일부 테이블이 있습니다. 사용자가 해당 테이블에 대한 일부 데이터를 제출하면 컨트롤러 메서드에 [Authorize]가 있으므로 User 개체를 얻습니다. User.Identity.Name으로 사용자 이름을 얻을 수 있지만 (소유권) 관계를 설정할 수있는 UserID를 얻으려면 어떻게해야합니까?
User 개체에서 가져올 수 없지만 다음과 같이 가져올 수 있습니다.
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
해결책은 다음과 같습니다.
포함:
using Microsoft.AspNet.Identity;
그런 다음 확장 방법을 사용합니다.
User.Identity.GetUserId();
첫째,이 답변은 엄격하게 MVC 답변이 아니라 ASP.NET 답변입니다. 이 경우 사이트가 MVC라는 사실은 문제 해결과 관련이 없습니다.
흠. 시스템에서 사용자를 어떻게 처리하고 있는지 잘 모르겠지만 asp.net membership provider
.net에서 기본 제공 되는 (매우 사악한) 사용하는 것처럼 들립니다 . 이것은 당신이 말한 사실에 의해 암시됩니다
- aspnet_Users.UserID
- UserID는 고유 식별자입니다 (읽기 : GUID).
기본 FormsIdentity 를 사용하는 기본 양식 인증 시스템을 사용 하면 올바르게 언급 한대로 Name 이라는 단일 속성 만 있습니다 . 이는 고유 한 사용자 정보를 배치 할 값이 하나뿐임을 의미합니다. 귀하의 경우 에는 속성 에 Name / UserName / DisplayName을 넣습니다 Name
. 이 이름이 표시 이름이고 고유하다고 가정합니다. 여기에 어떤 가치를 입력하든 고유해야 합니다.
이로부터 사용자의 GUID를 가져올 수 있습니다.
이것 좀 봐.
using System.Web.Security;
....
// NOTE: This is a static method .. which makes things easier to use.
MembershipUser user = Membership.GetUser(User.Identity.Name);
if (user == null)
{
throw new InvalidOperationException("User [" +
User.Identity.Name + " ] not found.");
}
// Do whatever u want with the unique identifier.
Guid guid = (Guid)user.ProviderUserKey;
따라서 사용자 정보를 가져 오려면 위의 정적 방법을 사용하여 데이터베이스에서 가져와야합니다.
MSDN 에서 Membership 클래스 및 MembershipUser 클래스 에 대한 모든 내용을 읽어보십시오 .
보너스 답변 / 제안
따라서 나는 그 결과를 캐치하여 데이터베이스를 계속 칠 필요가 없습니다.
... cont from above....
Guid guid = (Guid)user.ProviderUserKey;
Cache.Add(User.Identity.Name, user.UserID); // Key: Username; Value: Guid.
그렇지 않으면 고유 한 Identity 클래스 ( IIdentity 에서 상 속됨 )를 만들고 UserID
. 그런 다음 인증 할 때마다 (및 모든 요청에 대해)이 값을 설정할 수 있습니다. 어쨌든 이것은 하드 코어 솔루션이므로 지금 당장 캐싱으로 이동하십시오.
HTH
User.Identity
입니다 IPrincipal
- 일반적으로 유형의System.Web.Security.FormsIdentity
UserID에 대해 아무것도 알지 못합니다. 'ID'개념의 추상화 일뿐입니다.
IIdentity의 인터페이스는도하지, 사용자에 대한 '사용자 이름'을 '이름'이있다.
MVC4를 기본값으로 사용하는 경우 다음 SimpleMembershipProvider
을 수행 할 수 있습니다.
WebSecurity.GetUserId(User.Identity.Name) // User is on ControllerBase
( WebMatrix WebSecurity
의 nuget 패키지 Microsoft.AspNet.WebPages.WebData
에는
당신은 또한 사용할 수 있습니다
WebSecurity.CurrentUserName
WebSecurity.CurrentUserId
(당신이 사용하는 경우 ASPNetMembershipProvider 있는 나이가 더 복잡한 ASPNET 회원 시스템은 @ eduncan911하여 답을 참조)
ASP.NET Membership (IPrincipal 개체를 차례로 사용)을 사용하는 경우 :
using System.Web.Security;
{
MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name);
Guid guid = (Guid)user.ProviderUserKey;
}
User.Identity는 항상 로그인 여부에 관계없이 현재 사용자의 상태를 반환합니다.
익명 여부 등. 따라서 다음을 확인하십시오.
if (User.Identity.IsAuthenticated)
{
...
}
그래서, 모두 합치면 :
using System.Web.Security;
{
if (User.Identity.IsAuthenticated)
{
MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name);
Guid guid = (Guid)user.ProviderUserKey;
}
}
사용자 ID를 얻는 최상의 옵션
Add Below references
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;*
public myFunc()
{
.....
// Code which will give you user ID is
var tmp = User.Identity.GetUserId();
}
If you are using your own IPrincipal object for authorization, you just need to cast it to access the Id.
For example:
public class MyCustomUser : IPrincipal
{
public int UserId {get;set;}
//...Other IPrincipal stuff
}
Here is a great tutorial on creating your own Form based authentication.
http://www.codeproject.com/KB/web-security/AspNetCustomAuth.aspx
That should get you on the right path to creating an authentication cookie for your user and accessing your custom user data.
using System.Web.Security;
MembershipUser user = Membership.GetUser(User.Identity.Name);
int id = Convert.ToInt32(user.ProviderUserKey);
Its the ProviderUserKey property.
System.Web.Security.MembershipUser u;
u.ProviderUserKey
Simple....
int userID = WebSecurity.CurrentUserId;
Usually you can just use WebSecurity.currentUserId
, but if you're in AccountController just after the account has been created and you want to use the user id to link the user to some data in other tables then WebSecurity.currentUserId
(and all of the solutions above), unfortunately, in that case returns -1, so it doesn't work.
Luckily in this case you have the db context for the UserProfiles table handy, so you can get the user id by the following:
UserProfile profile = db.UserProfiles.Where(
u => u.UserName.Equals(model.UserName)
).SingleOrDefault();
I came across this case recently and this answer would have saved me a whole bunch of time, so just putting it out there.
참고URL : https://stackoverflow.com/questions/924692/how-do-you-get-the-userid-of-a-user-object-in-asp-net-mvc
'IT TIP' 카테고리의 다른 글
프로그래밍 방식으로 ProgressBar를 만드는 방법은 무엇입니까? (0) | 2020.10.25 |
---|---|
307 Chrome에서 analytics.js를로드 할 때 리디렉션 (0) | 2020.10.25 |
내 PHP 파일이 일반 텍스트로 표시되는 이유는 무엇입니까? (0) | 2020.10.25 |
콘솔 응용 프로그램을 닫는 명령? (0) | 2020.10.25 |
Android : 어떤 상황에서 대화 상자가 나타나 onPause ()가 호출됩니까? (0) | 2020.10.25 |