realist
realist

Reputation: 2385

.net core web API access variable in controller from other classes

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

Answers (2)

realist
realist

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

tmaj
tmaj

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:

  1. It's a common pattern
  2. Methods don't depend on a controller
  3. Passing it is actually less code than: var requestedUserId= StudentController.requestedUserId;?????

Upvotes: 1

Related Questions