Reputation: 2385
In my asp.net core web API, i want to access variable in my controller. The variable will set while GetAllStudents method running. StudentController and StudentRepository is in same solution but different project. How can i access from StudentRepository.cs to variable in StudentController.cs? There is some solution for MVC, but i can't find for web API. So, question is not duplicate.
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();
}
Upvotes: 1
Views: 2317
Reputation: 2385
I found the solution. The solution is "IHttpContextAccessor". You can inject by dependency injection and then you can use from everywhere (forexample dbcontext class)
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();
}
}
Upvotes: 0
Reputation: 35037
You can just pass it in.
GetAllStudents(int userId)
Update:
Re: Thanks for your reply. But this variable is used every method in every controller. So i don't want write everywhere (int userId).
You should pass it to every method that needs it:
var requestedUserId= StudentController.requestedUserId;?????
Upvotes: 1