asp.net core mvc의 다른 컨트롤러에서 GET 메서드에 액세스하는 방법은 무엇입니까?
Aug 18 2020
두 개의 컨트롤러가 있습니다 : OcorrenciasAPI 및 IgnicoesAPI. 내 컨트롤러 IgnicoesAPI에서 OcorrenciasAPI 컨트롤러를 통해 GET 메서드에 액세스해야합니다. 이를 수행하는 가장 좋은 방법은 무엇입니까?
답변
BijuKalanjoor Aug 18 2020 at 14:56
이것은 귀하의 질문에 대한 정확한 대답은 아니지만 문제를 해결할 수 있습니다. GET 메서드 내부의 코드를 공통 클래스로 재구성하고 두 컨트롤러에서이 클래스에 액세스합니다. 아래에 샘플 코드를 추가합니다.
모델
public sealed class Person
{
public int ID { get; set; }
public string Name { get; set; }
}
저장소
public class PersonRepository
{
public IEnumerable<Person> GetPeople()
{
return new List<Person>()
{
new Person{ID = 1, Name = "Name 1" },
new Person{ID = 2, Name = "Name 2" }
};
}
}
첫 번째 API 컨트롤러
[Route("api/[controller]")]
[ApiController]
public class MyFirstApiController : ControllerBase
{
private readonly PersonRepository personRepository = new PersonRepository();
[HttpGet]
public IEnumerable<Models.Person> Get()
{
return personRepository.GetPeople();
}
}
두 번째 API 컨트롤러
[Route("api/[controller]")]
[ApiController]
public class MySecoundApiController : ControllerBase
{
private readonly PersonRepository personRepository = new PersonRepository();
[HttpGet]
public IEnumerable<string> Get()
{
// Calling same repository here.
var people = personRepository.GetPeople();
return people.Select(p=> p.Name);
}
}
BruceAdams Aug 18 2020 at 14:58
공유 기능을 사용하여 새 클래스를 만들고 startup.cs에 서비스로 추가 한 다음 컨트롤러에 삽입합니다.
public interface IMyService
{
string MyMethod();
}
public class MyService : IMyService
{
public string MyMethod()
{
throw new NotImplementedException();
}
}
Startup.cs
services.AddTransient<IMyService, MyService>();
OcorrenciasAPI 생성자
private readonly IMyService _myService;
public OcorrenciasAPI (IMyService myService)
{
_myService = myService
}
IgnicoesAPI 생성자
private readonly IMyService _myService;
public IgnicoesAPI(IMyService myService)
{
_myService = myService
}
사용하다
var result = _myService.MyMethod();