问题
I have an MVC website that uses ASP.NET Identity. This site can be used for multiple customers data, and each customer is independent to another, no data should be shared. Each transaction should happen only on that customers data when that Customer is selected.
However, the Users who log in can see All customers, they just choose at login which customer to transact against.
So upon login, they will pick from a Dropdown their customer, and then see all that customers items, individual information, and unique things that can be done for that customer.
So for example
var allItems = from a in db.Items where a.CustomerId = customerId select a;
This customer Id can be got at login, as its what the User chose from a dropdown. However, how do I persist this choice throughout the entirety of the users log in session? I obviously don't want to save it to the database as its not a permanent choice I want the choice to be gone when they log out, with them to be free to choose another Customer next login.
Another cool thing would be able to override the get method in the DbContext to retreive only items matching whatever customer Id was selected on login
public DbSet<Item> ItemsAll { get; set; }
public IQueryable<Item> Items
{
get
{
return ItemsAll.Where(x => x.Customer == myLoggedInCustomerChoice);
}
}
回答1:
Add the value to a Session-variable, and check against it when you load pages.
回答2:
Your choices are
- Persist it to the database. Good for if you really never want to have the user choose again. The downside of this is if you want to also capture it on the client you need to also save the value on the client using one of the other choices.
- Persist it to a cookie. Don't set an expiration or set it to the same expiration as the authentication cookie where remember me is persisted .
- Persist it to the HTML5 local storage (window.localStorage). The downside here is you need to include any variables in any requests back the server where this information is used. This is not necessary with the other choices.
- Persist it in the Session object and configure Sessions to use a database. I am not a big fan of Session objects so I would use this as a last resort.
- Hidden field (input type='hidden') - Same downside as local storage BUT you have to make sure that this value is not lost in navigation. So this is fine for an SPA where some of the content remains static but not handy for a traditional web app.
来源:https://stackoverflow.com/questions/36009609/mvc-individual-user-accounts-login-value-persisting