Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 202
Chris Shouts Avatar asked Dec 21 '10 15:12

Chris Shouts


2 Answers

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.

like image 190
kevingessner Avatar answered Nov 16 '22 14:11

kevingessner


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.

like image 39
MikeWyatt Avatar answered Nov 16 '22 15:11

MikeWyatt