来自其他类的控制器中的.net核心Web API访问变量

问题描述 投票:1回答:2

在我的asp.net核心Web API中,我想在我的控制器中访问变量。当GetAllStudents方法运行时,该变量将设置。 StudentController和StudentRepository在同一个解决方案中,但项目不同。如何从StudentRepository.cs访问StudentController.cs中的变量? MVC有一些解决方案,但我找不到web API。所以,问题不重复。

StudentController.cs:

 int requestedUserId;

 [HttpGet("GetAllStudents")]
 public async Task<ServiceResult>GetAllStudents()
    {
        requestedUserId= context.HttpContext.Request.Headers["Authorization"];
        return await (studentService.GetAllStudents(requestedUserId));
    }

StudentService.cs:

 public async Task<ServiceResult> GetAllStudents()
    {
        return await unitOfWork.studentRepo.GetAllStudents();
    }

StudentRepository.cs:

public async Task<List<Student>> GetAllStudents()
    {
        ?????var requestedUserId= StudentController.requestedUserId;?????
        LogOperation(requestedUserId);
        return context.Students.ToList();
    }
c# asp.net-core asp.net-core-webapi
2个回答
1
投票

你可以把它传递进来。

GetAllStudents(int userId)


更新:

回复:谢谢你的回复。但是每个控制器中的每个方法都使用此变量。所以我不想在任何地方写(int userId)。

您应该将它传递给需要它的每个方法:

  1. 这是一种常见的模式
  2. 方法不依赖于控制器
  3. 传递它实际上比代码更少:var requestedUserId= StudentController.requestedUserId;?????

0
投票

我找到了解决方案。解决方案是“IHttpContextAccessor”。您可以通过依赖注入注入,然后您可以从任何地方使用(例如dbcontext类)

public class StudentService : IStudentService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public StudentService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

public async Task<List<Student>> GetAllStudents()
    {
        var requestedUserId= _httpContextAccessor.HttpContext.Headers["Authorization"];
        LogOperation(requestedUserId);
        return context.Students.ToList();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.