Переменная доступа к ядру .net core в контроллере других классов - PullRequest
0 голосов
/ 16 сентября 2018

В моем основном веб-API asp.net я хочу получить доступ к переменной в моем контроллере. Переменная будет установлена ​​во время работы метода GetAllStudents. StudentController и StudentRepository находятся в одном решении, но в другом проекте. Как я могу получить доступ из StudentRepository.cs к переменной в StudentController.cs? Есть какое-то решение для MVC, но я не могу найти для веб-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();
    }

Ответы [ 2 ]

0 голосов
/ 18 сентября 2018

Я нашел решение. Решение - «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();
    }
}
0 голосов
/ 16 сентября 2018

Вы можете просто передать его.

GetAllStudents(int userId)


Обновление:

Re: Спасибо за ваш ответ. Но эта переменная используется каждым методом в каждом контроллере. Так что я не хочу писать везде (int userId).

Вы должны передать его каждому методу, который в этом нуждается:

  1. Это обычная модель
  2. Методы не зависят от контроллера
  3. Передача кода на самом деле меньше, чем: var requestedUserId= StudentController.requestedUserId;?????
...