且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何显示基于MVC 4中当前登录用户的数据?

更新时间:2023-12-01 15:52:46

您可以尝试创建一个ApplicationUser类,该类从IdentityUser继承并具有要添加到该用户的任何自定义属性:

You can try creating a ApplicationUser class that inherits from IdentityUser with any custom properties you want to add to that user:

public class ApplicationUser : IdentityUser
{      
    public int CustomProperty { get; set; }
    ...
}

然后将ApplicationUser传递给dbcontext:

Then you pass the ApplicationUser to the dbcontext:

public class YourDbContext : IdentityDbContext<ApplicationUser>

当您想获取特定用户的数据时,只需获取登录用户的身份即可:

And when you want to get data for a specific user just get the Identity of the logged on user:

var userId = User.Identity.GetUserId();

_dbContext.YourTable.Where(x => x.UserId = userId); 

通过这种方式,您不必限制特定ID的路由,只需使用当前登录用户的ID即可获取所需的数据.

This way you don't have to restrict your routes for specific ids, just use the Id of the current logged on user to get the data you need.