Asp.net core 学习笔记 ( Web Api )

asp.net core 把之前的 webapi 和 mvc 做了结合. 

mvc 既是 api. 

但是后呢,又发现, api 确实有独到之处,所以又开了一些补助的方法.

namespace Project.Controllers
{
    public class PostForm
    {
        [Required]
        public IFormFile file { get; set; }
    }

    [ApiController] 
    [Route("api/[controller]")]
    public class ProductsController : ControllerBase 
    {
        private DB Db { get; set; }
        public ProductsController(DB db)
        {
            Db = db;
        }

        [HttpGet]
        public ActionResult<List<Product>> Get()
        {
            return Ok(Db.Products);
        }

        [HttpGet("{Id}")]
        [ProducesResponseType(400)]
        [ProducesResponseType(404)]
        public ActionResult<Product> GetById(string Id,[Required] string code)
        {
            return NotFound();            
        }

        [HttpPost]
        [ProducesResponseType(400)]
        public async Task<ActionResult<Product>> Post(Product product)
        {
            Db.Add(product);
            await Db.SaveChangesAsync();
            return Ok(product);
        }

        [HttpPost("upload")]
        [ProducesResponseType(400)]
        public ActionResult<string> Upload([FromForm] PostForm form)
        {
            return Ok("filename");
        } 
    }
}

继承的是 ControllerBase 而不是 MVC 常用的 Controller,这个类多了一些常用的 api 返回 Result, 比如 ok, badrequest 等等

[ApiController] 使用标签 ApiController 这个能自动做 model valid 检查, 自动 binding FromBody, FromQuery 等, 但 FromForm 还是要自己写哦, 如果你担心它的智能,也可以完全自己写. 

或则把它某个智能关掉 . Add the following code in Startup.ConfigureServices after services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);:

services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressConsumesConstraintForFormFileParameters = true;
    options.SuppressInferBindingSourcesForParameters = true;
    options.SuppressModelStateInvalidFilter = true;
});

[HttpPost("nextSegment")] 通过 http method 标签,我们可以很容易的写各做方法, 比如 get,post,put,delete, route 功能也包在内了真好呢. 

[ProducesResponseType] 这个标签主要功能是为了方便做 document, 配合 ActionResult<T> 泛型, 我们可以简单的表示正常情况下的返回,其余不正常情况使用 ProducesResponseType 来表示. 

通常是 404, 400 应该没有别的了吧.

猜你喜欢

转载自www.cnblogs.com/keatkeat/p/9297672.html