จะเข้าถึงเมธอด GET จากคอนโทรลเลอร์อื่นใน asp.net core mvc ได้อย่างไร
Aug 18 2020
ฉันมีตัวควบคุมสองตัว: OcorrenciasAPI และ IgnicoesAPI ฉันต้องการเข้าถึงเมธอด GET ในคอนโทรลเลอร์ IgnicoesAPI ของฉันผ่านตัวควบคุม OcorrenciasAPI แนวทางที่ดีที่สุดในการทำเช่นนี้คืออะไร?
คำตอบ
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();