How to show the data based on current logged in user in MVC 4? [closed]

為{幸葍}努か 提交于 2020-01-05 12:38:05

问题


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?

User   Id    Value

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

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.


回答1:


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; }
    ...
}

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); 

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.



来源:https://stackoverflow.com/questions/31624125/how-to-show-the-data-based-on-current-logged-in-user-in-mvc-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!