gpt4 book ai didi

c# - 如何从同一项目中的另一个 Api Controller 调用 Api Controller

转载 作者:行者123 更新时间:2023-12-01 21:54:51 25 4
gpt4 key购买 nike

我有一个对象“ApplicantDetail”,其中包含 ApplicantController 中的对象列表,我想将发布请求发送到 Personaldetails Api 以保存到数据库并获得响应

ApplicantController 上的 API

    // POST: api/ApplicantDetail
[HttpPost]
[Route("~/api/ApplicantDetail")]
public IActionResult Post([FromBody] Personaldetail ApplicantDetail)
{

Personaldetail personaldetail = new Personaldetail
{
Name = ApplicantDetail.Name,
Cnic = ApplicantDetail.Cnic,
Phone = ApplicantDetail.Phone
};

List<Address> addresses = new List<Address>();
List<Employee> employees = new List<Employee>();
List<Bank> banks = new List<Bank>();

addresses.AddRange(ApplicantDetail.Address);
employees.AddRange(ApplicantDetail.Employee);
banks.AddRange(ApplicantDetail.Bank);

var response = *//How to Call Personaldetail Post APi of PersonaldetailController Controller From Here and Get
response back//*

return null;
}

个人细节 Controller 上的API

    // POST: api/Personaldetails
[HttpPost]
public async Task<IActionResult> PostPersonaldetail([FromBody] Personaldetail personaldetail)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

_context.Personaldetail.Add(personaldetail);
await _context.SaveChangesAsync();

return CreatedAtAction("GetPersonaldetail", new { id = personaldetail.ApplicantId }, personaldetail);
}

最佳答案

您应该创建一个服务类来表示个人详细信息 API。在此类中,您将注入(inject) HttpClient,然后使用强类型客户端设置 IHttpClientFactory:

public class PersonalDetailsService
{
private readonly HttpClient _client;

public PersonalDetailsService(HttpClient client)
{
_client = client;
}

// methods here to interact with API via `_client`
}

然后,在 ConfigureServices 中:

services.AddHttpClient<PersonalDetailsService>(c =>
{
c.BaseAddress = new Uri(Configuration["PersonalDetailsAPIUrl"]);
// configure anything else you need to on the `HttpClient`
});

最后,在您的 Controller 中,注入(inject) PersonalDetailsS​​ervice:

[ApiController]
[Route("api/ApplicantDetail")]
public class ApplicantController
{
private readonly PersonalDetailsService _personalDetailsService;

public ApplicantController(PersonalDetailsService personalDetailsService)
{
_personalDetailsService = personalDetailsService;
}

[HttpPost("")]
public async Task<IActionResult> Post([FromBody] Personaldetail ApplicantDetail)
{
...

var response = await _personalDetailsService.SomeMethodAsync(someParam);

return null;
}
}

关于c# - 如何从同一项目中的另一个 Api Controller 调用 Api Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58504110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com