.Net Core WebApi(1)— 入门

主要讲述利用EF Core的CodeFirst迁移数据库,简单接口增删改查的使用,利用Swagger生成接口文档。

1.新建项目 创建DbContext 和实体模型
 
(1)添加类ToDoDbContext,继承DbContext
1     public class ToDoContext:DbContext
2     {
3         public ToDoContext(DbContextOptions options) : base(options)
4         {
5         }
6         public DbSet ToDoItems { get; set; }
7     }

(2) 添加类 ToDoItem

 1     public class ToDoItem
 2     {
 3         //自增标识
 4         public int ID { get; set; }
 5         /// 
 6         /// 名称
 7         /// 
 8         public string Name { get; set; }
 9         /// 
10         /// 是否完成
11         /// 
12         public bool IsCompleted { get; set; }
13     }

 

2.CodeFirst-数据库迁移 
(1)在“ appsettings.json”中,配置数据库连接字符串
1   "ConnectionStrings": {
2      "todoContext": "Server=.;DataBase=ToDoDataBase;uid=sa;pwd=密码"
3   },
(2)在启动项“ Startup.cs”中 添加映射关系
1  public void ConfigureServices(IServiceCollection services)
2         {
3             services.AddDbContext(opt =>  opt.UseSqlServer(Configuration.GetConnectionString("todoContext")));
4             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
5         }
(3)通过程序包控制台 数据库迁移
首先 导入Nuget包  Install-Package Microsoft.EntityFrameworkCore.Tools
然后 执行              Add-Migration InitDatabase
最后更新数据库     update-database
 
所有步骤后会在项目中生成一个新的Migrations文件
 
 
3.完成增删改查接口
 添加 空的Webapi控制器 ToDoController
 
 1   [Route("[controller]")]
 2     public class ToDoController : ControllerBase
 3     {
 4         private readonly ToDoContext context;
 5         //构造函数 初始化
 6         public ToDoController(ToDoContext context)
 7         {
 8             this.context = context;
 9             if (this.context.ToDoItems.Count() == 0)
10             {
11                 this.context.ToDoItems.Add(new ToDoItem { Name = "Item1" });
12                 this.context.SaveChanges();
13             }
14         }
15         //默认
16         [HttpGet]
17         public IEnumerable GetAll()
18         {
19             return context.ToDoItems.ToList();
20         }
21         [HttpGet("{id}",Name ="GetTodo")]
22         /// 
23         /// 根据Id获取
24         /// 
25         /// 
26         /// 
27         public IActionResult GetById(long id)
28         {
29             var item = context.ToDoItems.FirstOrDefault();
30             if (item == null)
31             {
32                 return NotFound();
33             }
34             return new ObjectResult(item);
35         }
36         /// 
37         /// 新增
38         /// 
39         /// 
40         /// 
41         [HttpPost]
42         public IActionResult Create([FromBody] ToDoItem item)
43         {
44             if (item == null)
45             {
46                 return BadRequest();
47             }
48             context.ToDoItems.Add(item);
49             context.SaveChanges();
50             return CreatedAtRoute("GetTodo", new { id = item.ID }, item);
51         }
52         /// 
53         /// 更新
54         /// 
55         /// 
56         /// 
57         /// 
58         [HttpPut("{id}")]
59         public IActionResult Update(long id, [FromBody] ToDoItem item)
60         {
61             if (item == null && item.ID != id)
62             {
63                 return BadRequest();
64             }
65             var model = context.ToDoItems.SingleOrDefault(t => t.ID == id);
66             if (model == null)
67             {
68                 return NotFound();
69             }
70             model.IsCompleted = item.IsCompleted;
71             model.Name = item.Name;
72             context.ToDoItems.Update(model);
73             context.SaveChanges();
74             return NoContent();
75         }
76         /// 
77         /// 删除
78         /// 
79         /// 
80         /// 
81         [HttpDelete("{id}")]
82         public IActionResult Delete(long id)
83         {
84             var todo = context.ToDoItems.FirstOrDefault(t => t.id == id);
85             if (todo == null)
86             {
87                 return NotFound();
88             }
89             context.ToDoItems.Remove(todo);
90             context.SaveChanges();
91             return new NoContentResult();
92         }
93     }
4.swagger接口文档生成 
Install-Package Swashbuckle.AspNetCore
 
(1)在“Startup.cs”中对swagger注入
 1 public void ConfigureServices(IServiceCollection services)
 2         {
 3             //swagger 配置
 4             services.AddSwaggerGen(c =>
 5             {
 6                 var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML";
 7                 var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
 8                 c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
 9             });
10             services.AddDbContext(opt =>  opt.UseSqlServer(Configuration.GetConnectionString("todoContext")));
11             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
12         }
13         /// 
14         /// 管道配置
15         /// 
16         /// 
17         /// 
18         // This method gets called by the runtime. Use this method to configure the HTTP  request pipeline.
19         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
20         {
21             if (env.IsDevelopment())
22             {
23                 app.UseDeveloperExceptionPage();
24             }
25             else
26             {
27                 // The default HSTS value is 30 days. You may want to change this for  production scenarios, see https://aka.ms/aspnetcore-hsts.
28                 app.UseHsts();
29             }
30             app.UseHttpsRedirection();
31             app.UseMvc();
32             // Enable middleware to serve generated Swagger as a JSON endpoint.
33             //启用中间件服务生成Swagger作为JSON终结点
34             app.UseSwagger();
35             // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the  Swagger JSON endpoint.
36             ////启用中间件服务对swagger-ui,指定Swagger JSON终结点
37             app.UseSwaggerUI(c =>
38             {
39                 c.ShowExtensions();
40                 
41                 c.SwaggerEndpoint("/swagger/v1/swagger.json", "test V1");
42             });
43          
44         }
45  

 

(2)右击项目,选择“属性”, 勾选“XML文档文件”,带出文档的注释
 
(3)运行程序,访问swagger,能够看到所有接口的说明,并进行接口调试

你可能感兴趣的:(.Net Core WebApi(1)— 入门)