Chris Shouts
Chris Shouts

Reputation: 5427

How To Get Current User in ASP.NET MVC Model

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

I am trying to figure out how to access the Current User from an ASP.NET MVC Model in a manner that is easy to unit test. The models are LINQ to SQL entities that are generated by SqlMetal.

The reason I think I need to know the Current User in the Model is because I want to restrict access to certain properties / methods based on that user's privileges.

I am open to adopting an alternative design and making whatever changes are necessary to implement this in a clean, unit test friendly manner.

Upvotes: 5

Views: 2589

Answers (3)

MikeWyatt
MikeWyatt

Reputation: 7871

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

Upvotes: 2

Chandu
Chandu

Reputation: 82903

I would Define a IUserService Interface with a GetUser method that would return a User Object and then define two implementations one for the actual application and one for a test scenario.

Upvotes: 0

kevingessner
kevingessner

Reputation: 18985

Managing permissions and restricting access to properties sounds like a job for the controller. The model's single responsibility is to store data, not to know about or manage users and permissions. So, in short, you don't need to get the current user in the model.

Upvotes: 5

Related Questions