如何显示基于MVC 4中当前登录用户的数据? [英] How to show the data based on current logged in user in MVC 4?

查看:117
本文介绍了如何显示基于MVC 4中当前登录用户的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有Entity Framework的基于登录身份验证的asp.net MVC 4应用程序.在这里,用户可以自己注册并在应用程序中添加自己的记录.

I have login authentication based asp.net MVC 4 application with Entity Framework. Here, user can get registered themselves and add their own records in the application.

因此,无论何时他们登录,他们都应该只看到自己的记录,而不是其他人.希望根据当前登录用户过滤记录.

So, Whenever they are logging in, they should just see their own records and not others. Would like to filter the records based on current logged user.

有没有一种简单的方法可以做到而又不影响性能?是否可以在一个地方处理这种情况?

Is there any simple approach that we can do it without affecting the performance? Is it possible to do it one place to handle this scenario?

用户   Id   值

User   Id    Value

1     1      测试值1
2     2       测试值2
2的3的测试值
1     4      xyzabc

1      1      Test value of 1
2      2      Test value of 2
2      3      Test value of 3
1      4      xyzabc

此外,需要通过查看URL命中来限制用户2 前任 : http://wesite.com/Details/1

Also, Need to restrict the user 2 by viewing the by url hits Ex : http://wesite.com/Details/1 and http://wesite.com/Details/4 should not be viewed by user 2 and vice-versa.

推荐答案

您可以尝试创建一个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.

这篇关于如何显示基于MVC 4中当前登录用户的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆