在我的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();
}
你可以把它传递进来。
GetAllStudents(int userId)
更新:
回复:谢谢你的回复。但是每个控制器中的每个方法都使用此变量。所以我不想在任何地方写(int userId)。
您应该将它传递给需要它的每个方法:
var requestedUserId= StudentController.requestedUserId;?????
我找到了解决方案。解决方案是“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();
}
}