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

更新 : 2019-06-03 

web api 返回 json 的情况下默认会把属性 PascalCase 变成 camelCase 很贴心哦. 

如果你不喜欢可以修改它 

  services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())

但是这个对 odata 的 response 是没有影响的哦, odata 不会自动 camelCase 的.

 

 

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. Controller 会继承 ControllerBase

[ApiController], 使用标签 ApiController 会开启自动 model valid 检查, 自动 binding FromBody, FromQuery 等, 但 FromForm 还是要自己写哦 (默认 api 都是 json 的嘛) , 如果你担心它的智能,也可以完全自己写. 

或则把它某个智能关掉 . 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 应该没有别的了吧.

 

转载于:https://www.cnblogs.com/keatkeat/p/9297672.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值