经过身份验证的用户和服务层

时间:2013-02-04 08:25:50

标签: asp.net-mvc model-view-controller asp.net-mvc-4 separation-of-concerns service-layer

我有一个MVC 4应用程序,它在不同的类库中使用服务层。

对该服务层的一些调用需要知道哪些用途正在请求数据。

数据记录因用户角色而异。

For Prevent Coupling Issue ,我应该在请求中传递用户名(HttpContext.User.Identity.Name),还是应该使用相同的HttpContext.User.Identity直接在服务层上访问它.Name。

我不确定是否应该从服务层隐藏HttpContext。

2 个答案:

答案 0 :(得分:3)

只需将当前经过身份验证的用户作为参数传递到服务层即可。切勿在服务层中使用HttpContext.User.Identity.Name

例如:

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

您的服务层永远不应与HttpContext绑定。

答案 1 :(得分:1)

将HttpContext传递给服务层可能看起来很诱人,但这将是一个糟糕的选择。它将在ASP.net运行时服务和业务逻辑之间建立一个硬链接(这正是你试图避免的,我假设)。最好的方法是创建表示登录用户的类,您可以在基本控制器中填充该类并将其传递给服务层。

通过这种方式,你可以获得两全其美的效果