I have a bit of a dilemma. We are choosing our DBContext using a dynamic builder. This is done because in the current database structure we have a separate server for every “Customer”. All of these Customer Databases use the same model so they are all exactly the same structure.
Enter picking the context to use with each call. We are using WebApi 2 and angular.
What we do is on the first “page” you pick your customer and we pass the customerId down and I need to store this value until the user decides to swap. That being said Session and WebApi2 are not friends.
I have a base repository that needs the customerId every time a call is made to one of the repositories. We have to verify that we are using the right context for that customer.
So…. That’s where I am.
Should I break the rules and use Session to store the customerId? I could use my DI container to inject an instance of HttpContext.Current into every call so that I would ignore the fact that session is null on a WebApiController.
Is there another way to handle this?
I would store this next to your authentication.
If you are using OAuth 2.0 Tokens for example you could add an Claim where you set the customerId. If you are using cookie based authentication I would set the customerId inside a cookie and resolve it every request.
This way you don’t keep any state on your server, but always have the CustomerId available. Because the user sends you the data in every request.
Next you could write a DelegatingHandler where you resolve the CustomerId. Then you could add it as a claim to the current user (ClaimsPrincipal) or whatever fits your framework. This is also a nice place to reject any requests that don’t include a customerId.
But much off this depends on the way you handle your authentication logic.