core webapi 基本使用

阅读: 评论:0

 core webapi 基本使用

< core webapi 基本使用

Restful 比较复杂,产出低,虽然 设计 api 需要遵循,但是为了出活等原因,可以灵活考虑。

下面的 基本设计,完全经验之谈,可不遵循,根据实际考虑 自己和公司状态 自我调整

1.添加测试实体 Person.cs

namespace aspnetcore003
{public record Person(int id , string name , int age);
}

2.添加测试 控制器PersonController.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Xml.Linq;namespace aspnetcore003.Controllers
{//路由加上[action] swagger 会显示每个方法名称 如:api/Person/GetAllPersn//默认为 [Route("api/[controller]")] 只显示 PersonController 的 Person 如 api/Person//并且所有的api接口都是api/Person[Route("api/[controller]/[action]")][ApiController]public class PersonController : ControllerBase{//如果在 Controller中使用 public 方法 并且没有加上 [HttpGet]等标记 swagger会报错//默认 swagger Controller中不支持 public公开方法,如果非要使用可以 改为 private//或者加入  [ApiExplorerSettings(IgnoreApi =true)] 忽略[ApiExplorerSettings(IgnoreApi =true)]public void Test(){//会报错}[HttpGet] //如果api接口没有定义 [HttpGet]等方法  会直接报错public Person[] GetAllPersn(){Test();return new Person[3]{new Person(1,"张三",18),new Person(1,"李四",28),new Person(1,"王五",38),};}[HttpGet]public Person? GetSinglePerson(int id){switch (id){case 1:return new Person(1, "张三", 18);case 2:return new Person(1, "李四", 28);case 3:return new Person(1, "王五", 38);}return null;}[HttpPost]public string AddPerson(Person person){return "添加成功";}[HttpDelete]public string DeletePerson(int id){return "删除成功";}}
}

本文发布于:2024-02-01 18:55:02,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170678490438743.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:net   asp   webapi   core
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23