1.打开VS 新建项目 ASP.NET Core Web API 项目
2.把默认示例(WeatherForecast)删除
3.新建一个API空 控制器
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication2.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class TestController : ControllerBase
{
[HttpGet]
public string test()
{
return "123";
}
}
}
Route 上加 action
每个action 都要添加http请求方式
4.新建Model 文件夹 以及TestModel
namespace WebApplication2.Model
{
public class TestModel
{
public int Id { get; set; }
public string? Code { get; set; }
public string? Name { get; set; }
public Boolean State { get; set; }
public string? Remark { get; set; }
}
}
在WebApplication2中添加
[HttpGet]
public List<TestModel> getList()
{
List<TestModel> list = new List<TestModel>();
list.Add(new TestModel() { Id = 1, Code = "test1", Name = "张无忌", State = true, Remark = "我是张无忌" });
list.Add(new TestModel() { Id = 2, Code = "test2", Name = "张三丰", State = true, Remark = "我是张三丰" });
return list;
}
返回的JSON首字母大写 和 时间格式
安装JSON
在Projram.cs中添加
builder.Services.AddControllers().AddNewtonsoftJson(option =>
{
option.SerializerSettings.ContractResolver = new DefaultContractResolver();
option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
});
添加swagger 注释
右键项目 属性=》生成=》输出=》文档文件
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(option =>
{
var file = Path.Combine(AppContext.BaseDirectory, "WebApplication1.xml");
option.IncludeXmlComments(file, true);
});
在action上添加
/// <summary>
/// 获取一个数组
/// </summary>
/// <returns></returns>