Question

I have a MVC 4 application which uses a Service Layer in a different class library.

Some of the calls to that service layer needs to know which uses is requesting the data.

The data records is different depending on the User Roles.

For Prevent Coupling Issue, Should I pass the username in the request (HttpContext.User.Identity.Name) or should I access it directly on the service layer using the same HttpContext.User.Identity.Name .

I am never sure if I should hide the HttpContext from the service layer.

Was it helpful?

Solution

Simply pass the currently authenticated user as parameter to your service layer. Never use HttpContext.User.Identity.Name in your service layer.

For example:

[Authorize]
public ActionResult SomeAction()
{
    string user = User.Identity.Name;
    this.someService.SomeOperation(user);
    ...
}

Your service layer should never be tied to an HttpContext.

OTHER TIPS

Passing HttpContext to the service layer may look tempting, but would be a bad choice. It would make a hard link between ASP.net runtime services and the business logic (this is exactly what you are trying to avoide, i assume). The best would be to create class to represent the logged in user, which you can populate in a base controller and pass that on to the service layer.

This way, you get best of both worlds

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top