How to get current user in ASP.NET MVC model

In my opinion, this is not a duplicate of How to get the current user in Asp.Net MVC .

I am trying to figure out how to access the current user from an ASP.NET MVC model so that it is easy to unit test. Models are LINQ to SQL objects that are generated by SqlMetal.

I think I need to know the current user in the model because I want to restrict access to certain properties / methods based on these user privileges.

I am open to accepting an alternative design and making any changes necessary to implement it in a clean, unit test friendly manner.

+5
source share
3 answers

Managing permissions and restricting access to properties sounds like a task for the controller. The model is solely responsible for storing data, and also not for knowing or managing users and permissions. So, in short, you do not need to get the current user in the model.

+5
source

I have always created new instances of my service classes for each instance of the controller. Given this, you can simply pass the service constructor to the current user to make it available to the rest of your model. If you show the current user as a property in your service interfaces, you can easily mock him for testing.

+2

I would define an IUserService interface with the GetUser method, which would return a user object, and then define two implementations for the real application and one for the test case.

0
source

All Articles