text 在.net核心中创建api控制器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 在.net核心中创建api控制器相关的知识,希望对你有一定的参考价值。

1. create a api controller
for example, create OrdersController.cs

[Route("api/[Controller]")] **map route**
public class OrdersController : Controller
{
    private readonly IDutchRepository repository;
    private readonly ILogger<OrdersController> logger;

    public OrdersController(IDutchRepository repository, ILogger<OrdersController> logger)
    {
        this.repository = repository;
        this.logger = logger;
    }

    [HttpGet]
    public IActionResult Get()
    {
        try
        {
            return Ok(this.repository.GetAllOrders());
        }
        catch (Exception ex)
        {
            this.logger.LogError($"Fail to get orders: {ex}");
            return BadRequest();
        }
    }

    [HttpGet("{id:int}")]
    public IActionResult Get(int id) {
        try
        {
            var order = this.repository.GetOrderById(id);
            if (order != null) return Ok(order);
            else return NotFound();
        }
        catch (Exception ex)
        {
            this.logger.LogError($"Fail to get orders: {ex}");
            return BadRequest();
        }
    }
}

2. add method of GetOrderById(id) and GetAllOrders() to repository interface and file
for example:
IDutchRepository file

public interface IDutchRepository
{
    IEnumerable<Product> GetAllProducts();
    IEnumerable<Product> GetProductsByCategory(string category);
    IEnumerable<Order> GetAllOrders();
    Order GetOrderById(int id);

    bool SaveAll();
}

DutchRepository file

public IEnumerable<Order> GetAllOrders()
{
    return this.context.Orders
        .Include(o => o.Items)
        .ThenInclude(i => i.Product)
        .ToList();
}

public Order GetOrderById(int id)
{
    return this.context.Orders
   .Where(o => o.Id == id)
   .Include(o => o.Items)
   .ThenInclude(i => i.Product)
   .FirstOrDefault();
}

3. solve reference loop problem, when include items(OrderItem) in Order, orderItem will refer order, 
it will cause infinite loop -- see ViewModel

Solution: in Startup.cs

in ConfigureServices method

services.AddMvc()
.AddJsonOptions(opt => opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

4. handle post, add post method in OrdersController

[HttpPost]
**FromBody is from post body -- for example, in postman post body**
public IActionResult Post([FromBody]Order model) {
    try
    {
        this.repository.AddEntity(model);
        if(this.repository.SaveAll())
        {
            return Created($"/api/orders/{model.Id}", model);
        }   
    }
    catch (Exception ex)
    {
        this.logger.LogError($"Fail to save a order: {ex}");
    }
    return BadRequest("Fail to save order");
}

IDutchRepository file

void AddEntity(object model);

DutchRepository file

public void AddEntity(object model)
{
    this.context.Add(model);
}

5. in postman, switch to POST --> BODY
write 
{
	"orderDate": "2015-06-06"
}
and click send

new order will be created

以上是关于text 在.net核心中创建api控制器的主要内容,如果未能解决你的问题,请参考以下文章

text 将文件从Angular发送到.net核心api控制器

在 web api 控制器(.net 核心)中使用 async/await 或任务

如何在asp.net核心中从客户端调用web api方法?

我们如何在 .net 核心控制台应用程序中存储加密的 API 密钥

如何通过 Gmail API 从 .net 核心控制台应用程序发送电子邮件?

text .net核心调用api(使用oauth 2.0)