Call one Web API through another Web API in .NetCore . I have Created two Web Api projects Catalog and Order i want to call catalog api through order

huangapple go评论68阅读模式
英文:

Call one Web API through another Web API in .NetCore . I have Created two Web Api projects Catalog and Order i want to call catalog api through order

问题

以下是您要翻译的代码部分:

//Order.api --OrderController
using System.Net;
using Microsoft.AspNetCore.Mvc;
using OrderApi.Entities;
using OrderApi.Repositories;

namespace OrderApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class OrderController : ControllerBase
    {
        private readonly IOrderRepository _repository;
        private readonly ILogger<OrderController> _logger;
        public OrderController(IOrderRepository repository, ILogger<OrderController> logger)
        {
            _repository = repository ?? throw new ArgumentNullException(nameof(repository));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }
        [HttpGet]
        [ProducesResponseType(typeof(IEnumerable<Order>), (int)HttpStatusCode.OK)]
        public async Task<ActionResult<IEnumerable<Order>>> GetOrders()
        {
            var orders = await _repository.GetOrders();
            return Ok(orders);
        }

        [HttpGet("{id}", Name = "GetOrder")]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        [ProducesResponseType(typeof(IEnumerable<Order>), (int)HttpStatusCode.OK)]
        public async Task<ActionResult<IEnumerable<Order>> GetOrderById(string id)
        {
            var order = await _repository.GetOrder(id);
            if (order == null)
            {
                _logger.LogError($"Product with id :{id} , not found.");
                return NotFound();
            }
            return Ok(order);
        }
    }
}

//Catalog.api --CatalogController
using System.Net;
using CatalogAPI.Entities;
using CatalogAPI.Repositories;
using Microsoft.AspNetCore.Mvc;

namespace CatalogAPI.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class CatalogController : ControllerBase
    {
        private readonly IProductRepository _repository;
        private readonly ILogger<CatalogController> _logger;
        public CatalogController(IProductRepository repository, ILogger<CatalogController> logger)
        {
            _repository = repository ?? throw new ArgumentNullException(nameof(repository));
            _logger = logger ?? throw a ArgumentNullException(nameof(logger));
        }
        [HttpGet]
        [ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)]
        public async Task<ActionResult<IEnumerable<Product>> GetProducts()
        {
            var products = await _repository.GetProducts();
            return Ok(products);
        }

        [HttpGet("{id}", Name = "GetProduct")]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        [ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)]
        public async Task<ActionResult<IEnumerable<Product>> GetProductById(string id)
        {
            var product = await _repository.GetProduct(id);
            if (product is null)
            {
                _logger.LogError($"Product with id :{id} , not found.");
                return NotFound();
            }
            return Ok(product);
        }

        [Route("[action]/{category}", Name = "GetProductByCategory")]
        [HttpGet]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        [ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)]
        public async Task<ActionResult<IEnumerable<Product>> GetProductByCategory(string category)
        {
            var products = await _repository.GetProductByCategory(category);
            return Ok(products);
        }

        [Route("[action]/{name}", Name = "GetProductByName")]
        [HttpGet]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        [ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)]
        public async Task<ActionResult<IEnumerable<Product>> GetProductByName(string name)
        {
            var items = await _repository.GetProductByName(name);
            if (items == null)
            {
                _logger.LogError($"Product with name : {name} , not found.");
                return NotFound();
            }
            return Ok(items);
        }

        [HttpPost]
        [ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)]
        public async Task<ActionResult<IEnumerable<Product>> CreateProduct([FromBody] Product product)
        {
            await _repository.CreateProduct(product);
            return CreatedAtRoute("GetProduct", new { id = product.Id }, product);
        }

        [HttpPut]
        [ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)]
        public async Task<ActionResult<IEnumerable<Product>> UpdateProduct([FromBody] Product product)
        {
            return Ok(await _repository.UpdateProduct(product));
        }

        [HttpDelete]
        [ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)]
        public async Task<ActionResult<IEnumerable<Product>> DeleteProductByID(string id)
        {
            return Ok(await _repository.DeleteProduct(id));
        }
    }
}

请注意,我只翻译了您提供的代码部分,没有回答其他问题。如果您需要进一步的帮助或有其他问题,请随时提问。

英文:

//Order.api --OrderController

using System.Net;
using Microsoft.AspNetCore.Mvc;
using OrderApi.Entities;
using OrderApi.Repositories;
namespace OrderApi.Controllers;
[ApiController]
[Route(&quot;api/[controller]&quot;)]
public class OrderController : ControllerBase
{
private readonly IOrderRepository _repository;
private readonly ILogger&lt;OrderController&gt; _logger;
public OrderController(IOrderRepository repository , ILogger&lt;OrderController&gt; logger )
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
[HttpGet]
[ProducesResponseType(typeof(IEnumerable&lt;Order&gt;) , (int)HttpStatusCode.OK)]
public async Task&lt;ActionResult&lt;IEnumerable&lt;Order&gt;&gt;&gt; GetOrders()
{
var orders = await _repository.GetOrders();
return Ok(orders);
}
[HttpGet(&quot;{id}&quot;, Name = &quot;GetOrder&quot;)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
[ProducesResponseType(typeof(IEnumerable&lt;Order&gt;), (int)HttpStatusCode.OK)]
public async Task&lt;ActionResult&lt;IEnumerable&lt;Order&gt;&gt;&gt; GetOrderById(string id)
{
var order = await _repository.GetOrder(id);
if (order == null)
{
_logger.LogError($&quot;Product with id :{id} , not found.&quot;);
return NotFound();
}
return Ok(order);
}
}

//Catalog.api --CatalogController

using System.Net;
using CatalogAPI.Entities;
using CatalogAPI.Repositories;
using Microsoft.AspNetCore.Mvc;
namespace CatalogAPI.Controllers;
[ApiController]
[Route(&quot;api/[controller]&quot;)]
public class CatalogController : ControllerBase
{
private readonly IProductRepository _repository;
private readonly ILogger&lt;CatalogController&gt; _logger;
public CatalogController(IProductRepository repository, ILogger&lt;CatalogController&gt; logger)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
[HttpGet]
[ProducesResponseType(typeof(IEnumerable&lt;Product&gt;), (int)HttpStatusCode.OK)]
public async Task&lt;ActionResult&lt;IEnumerable&lt;Product&gt;&gt;&gt; GetProducts()
{
var products = await _repository.GetProducts();
return Ok(products);
}
/*  */
[HttpGet(&quot;{id}&quot;, Name = &quot;GetProduct&quot;)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
[ProducesResponseType(typeof(IEnumerable&lt;Product&gt;), (int)HttpStatusCode.OK)]
public async Task&lt;ActionResult&lt;IEnumerable&lt;Product&gt;&gt;&gt; GetProductById(string id)
{
var product = await _repository.GetProduct(id);
if (product == null)
{
_logger.LogError($&quot;Product with id :{id} , not found.&quot;);
return NotFound();
}
return Ok(product);
}
[Route(&quot;[action]/{category}&quot;, Name = &quot;GetProductByCategory&quot;)]
[HttpGet]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
[ProducesResponseType(typeof(IEnumerable&lt;Product&gt;), (int)HttpStatusCode.OK)]
public async Task&lt;ActionResult&lt;IEnumerable&lt;Product&gt;&gt;&gt; GetProductByCategory(string category)
{
var products = await _repository.GetProductByCategory(category);
return Ok(products);
}
[Route(&quot;[action]/{name}&quot;, Name = &quot;GetProductByName&quot;)]
[HttpGet]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
[ProducesResponseType(typeof(IEnumerable&lt;Product&gt;), (int)HttpStatusCode.OK)]
public async Task&lt;ActionResult&lt;IEnumerable&lt;Product&gt;&gt;&gt; GetProductByName(string name)
{
var items = await _repository.GetProductByName(name);
if (items == null)
{
_logger.LogError($&quot;Product with name : {name} , not found.&quot;);
return NotFound();
}
return Ok(items);
}
[HttpPost]
[ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)]
public async Task&lt;ActionResult&lt;IEnumerable&lt;Product&gt;&gt;&gt; CreateProduct([FromBody] Product product)
{
await _repository.CreateProduct(product);
return CreatedAtRoute(&quot;GetProduct&quot;, new { id = product.Id }, product);
}
[HttpPut]
[ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)]
public async Task&lt;ActionResult&lt;IEnumerable&lt;Product&gt;&gt;&gt; UpdateProduct([FromBody] Product product)
{
return Ok(await _repository.UpdateProduct(product));
}
[HttpDelete]
[ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)]
public async Task&lt;ActionResult&lt;IEnumerable&lt;Product&gt;&gt;&gt; DeleteProductByID(string id)
{
return Ok(await _repository.DeleteProduct(id));
}
}

These are the two Controller classes of the given Web api projects. How should i call the Web api proj of catalog api through Orderapi proj. Can someone explain it in steps or probably provide a code for it and packages I need to add . I have gone through few blogs but i haven't got any particular solution for it.

答案1

得分: 1

使用HttpClient类从Order API调用Catalog API的最简单方法是使用HttpClient类。以下是一个示例,展示了如何从Order API中调用Catalog API的GET端点:

  1. OrderController类中,创建一个HttpClient类的实例,并将其BaseAddress属性设置为Catalog API的URL。

    private readonly HttpClient _httpClient;
    
    public OrderController()
    {
        _httpClient = new HttpClient();
        _httpClient.BaseAddress = new Uri("http://your-catalog-api-url.com/");
    }
    
  2. 在控制器操作方法中,使用HttpClient实例来调用Catalog API中的GET端点。

    private readonly HttpClient _httpClient;
    
    public OrderController()
    {
        _httpClient = new HttpClient();
        _httpClient.BaseAddress = new Uri("http://your-catalog-api-url.com/");
    }
    
    [HttpGet("{id}")]
    public async Task<IActionResult> GetOrder(int id)
    {
        var response = await _httpClient.GetAsync($"api/catalog/products/{id}");
    
        if (response.IsSuccessStatusCode)
        {
            var product = await response.Content.ReadAsAsync<Product>();
            return Ok(product);
        }
    
        return NotFound();
    }
    

注意:

  1. 你应该将*your-catalog-api-url.comapi/catalog/products/{id}替换为你想要调用的Catalog API的实际端点URL。你可以使用Options模式来进行配置。

  2. 最好使用依赖注入来配置HttpClient(你也可以使用IHttpClientFactory)。

  3. 你可能需要将访问令牌添加到Order API请求的标头中,并在Catalog API中配置CORS以允许通信。

  4. 这是最简单的解决方案。然而,对于这种情况,还有更好的解决方案,以解耦Order API和Catalog API,并提高可扩展性和可靠性。其中一个解决方案是使用消息队列,例如RabbitMQ、Azure Service Bus等。

英文:

The easiest way to call the Catalog API from the Order API is to use the HttpClient class. Here's an example of how you can call a GET endpoint in the Catalog API from the Order API:

  1. In the OrderController class, create an instance of the HttpClient class and set its BaseAddress property to the Catalog API URL.

    private readonly HttpClient _httpClient;
    public OrderController()
    {
    _httpClient = new HttpClient();
    _httpClient.BaseAddress = new Uri(&quot;http://your-catalog-api-url.com/&quot;);
    }
    
  2. In a controller action method, use the HttpClient instance to call a GET endpoint in the Catalog API.

    private readonly HttpClient _httpClient;
    public OrderController()
    {
    _httpClient = new HttpClient();
    _httpClient.BaseAddress = new Uri(&quot;http://your-catalog-api-url.com/&quot;);
    }
    [HttpGet(&quot;{id}&quot;)]
    public async Task&lt;IActionResult&gt; GetOrder(int id)
    {
    var response = await _httpClient.GetAsync($&quot;api/catalog/products/{id}&quot;);
    if (response.IsSuccessStatusCode)
    {
    var product = await response.Content.ReadAsAsync&lt;Product&gt;();
    return Ok(product);
    }
    return NotFound();
    }
    

Notes:

  1. You should replace *your-catalog-api-url.com and api/catalog/products/{id} with the actual endpoints URLs of the Catalog API that you want to call. You could use the Options pattern for that.

  2. It is better to use Dependency Injection to configure the HttpClient (you could also use IHttpClientFactory).

  3. You might need to add the access token to the header of request in Order API and configure CORS in Catalog API to allow the communication.

  4. This is the easiest solution. There are, however, better ones for such cases to decouple the Order API and Catalog API and improve scalability and reliability. One is to use message queues, such as RabbitMQ, Azure Service Bus etc.

huangapple
  • 本文由 发表于 2023年2月24日 14:45:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定