工具为:vs2019
依赖项:通过NuGet 安装:Swashbuckle.AspNetCore 4.0.1
StartUp配置项如下:
using aspnetcorehellowould.Filter;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;
using System.IO;
namespace aspnetcorehellowould
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(Options =>
{
Options.Filters.Add<ExceptionFilter>();
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//注册Swagger生成器,定义一个和多个Swagger 文档
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "chenchangzhu's API",
Description = "学生管理学系统 web api",
TermsOfService = "大神在此,全给我站住唱征服",
Contact = new Contact
{
Name = "dashen",
Email = "xxxxx@qq.com",
Url = "http://www.baidu.com/"
},
License = new License
{
Name = "请说我好帅",
Url = "http://www.baidu.com/"
}
});
// 为 Swagger JSON and UI设置xml文档注释路径
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
var xmlPath = Path.Combine(basePath, "SwaggerDemo.xml");
c.IncludeXmlComments(xmlPath, true);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
//启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();
//启用中间件服务对swagger-ui,指定Swagger JSON终结点
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "zcc V1"));
}
}
}
web Api以学生和老师为例:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
namespace aspnetcorehellowould.Controllers
{
/// <summary>
/// 学生相关服务
/// </summary>
[Route("api/student")]
[ApiController]
public class StudentController : ControllerBase
{
private IEnumerable<Entity.Student> CreateStudents()
{
List<Entity.Student> list = new List<Entity.Student>();
for (int i = 0; i < 12; i++)
{
Entity.Student student = new Entity.Student();
student.Id = i;
student.Name = "小强" + i;
student.Age = 10 + i;
student.Sex = "男";
list.Add(student);
}
return list;
}
/// <summary>
/// 获取所有学生列表
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult<IEnumerable<Entity.Student>> Get()
{
return new JsonResult(CreateStudents());
}
// GET api/student/5
/// <summary>
/// 获取当个学生
/// </summary>
/// <param name="id">学生ID</param>
/// <returns></returns>
[HttpGet("{id}")]
public ActionResult<IEnumerable<Entity.Student>> Get(int id)
{
IEnumerable<Entity.Student> list = CreateStudents();
//你好 ya ya asdfsd 好像你很牛逼
return list.Where(s => s.Id == id).ToList();
}
// POST api/student
/// <summary>
/// 新增单个学生
/// </summary>
/// <param name="student">学生信息</param>
[HttpPost]
public ActionResult<IEnumerable<Entity.Student>> Post([FromBody] Entity.Student student)
{
List<Entity.Student> list = CreateStudents() as List<Entity.Student>;
list.Add(student);
return new JsonResult(list);
}
/// <summary>
/// 修改单个学生
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
// PUT api/student/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
//想想还是挺容易的
}
// DELETE api/student/5
/// <summary>
/// 删除单个学生
/// </summary>
/// <param name="id">学生ID</param>
[HttpDelete("{id}")]
public ActionResult<IEnumerable<Entity.Student>> Delete(int id)
{
List<Entity.Student> list = CreateStudents() as List<Entity.Student>;
//获取需要移除的ID
Entity.Student delObj = list.Where(s => s.Id == id).ToList()[0];
list.Remove(delObj);
return new JsonResult(list);
}
}
}
using aspnetcorehellowould.Filter;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace aspnetcorehellowould.Controllers
{
/// <summary>
/// 老师相关服务
/// </summary>
[Route("api/teacher")]
[ApiController]
public class TeacherController : Controller
{
// GET: api/<controller>
/// <summary>
/// 获取所有学生
/// </summary>
/// <returns></returns>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
/// <summary>
/// 获取单个老师信息
/// </summary>
/// <param name="id">老师ID</param>
/// <returns></returns>
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/<controller>
/// <summary>
/// 新增老师信息
/// </summary>
/// <param name="value">老师名称</param>
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
throw new BusinessException("相关信息不存在:" + id + " 不允许删asdf除!");
}
}
}
F5运行或者选择项目右击单例调试接口:
默认启动为http://localhost:4625/api/student,切换到swagger查看web api的话,只要将api/student改为swagger/index.html.
swagger默认页为index.html,这个和java有点区别,java为swagger-ui.htm.