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

use*_*508 3 model-view-controller asp.net-mvc separation-of-concerns service-layer asp.net-mvc-4

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

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

数据记录根据用户角色的不同而不同。

为了防止耦合问题,我应该在请求中传递用户名(HttpContext.User.Identity.Name)还是应该使用相同的 HttpContext.User.Identity.Name 在服务层上直接访问它。

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

Dar*_*rov 6

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

例如:

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

您的服务层永远不应该与HttpContext.

  • 不,不应该。服务层不应有任何对 System.Web 的引用。 (4认同)