新建.net core webApi接口

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值