问题
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