使用 ASP.NET Core MVC 创建 Web API(二)
使用 ASP.NET Core MVC 创建 Web API
使用 ASP.NET Core MVC 创建 Web API(一)
六、添加数据库上下文
数据库上下文是使用Entity Framework Core功能的主类。 此类由 Microsoft.EntityFrameworkCore.DbContext 类派生而来。
1) 在Visual Studio 2017的“解决方案资源管理器”中,右键单击“Models”文件夹,然后选择“添加” > “类”。 将类命名为 BookContext,然后单击“添加”。
2) 在Visual Studio 2017的“解决方案资源管理器”中使用鼠标双击打开BookContext.cs文件,并输入以下代码:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace BookApi.Models
{ public class BookContext: DbContext
{ public BookContext(DbContextOptions<BookContext> options)
: base(options)
{
} public DbSet<Book> Book { get; set; } }
}
七、注册数据库上下文
在 ASP.NET Core 中,服务(如数据库上下文)必须向依赖关系注入 (DI) 容器进行注册。该容器向控制器提供服务。
在Visual Studio 2017中的“解决方案资源管理器”中找到 Startup.cs文件,双击打开之后,添加将数据库上下文注入到DI容器中的代码。代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BookApi.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; namespace BookApi
{ 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.AddDbContext<BookContext>(options => options.UseSqlServer(Configuration.GetConnectionString("BookContext")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
} // 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();
}
app.UseMvc();
}
}
}
八、添加数据库连接
在Visual Studio 2017中的“解决方案资源管理器”中找到 appsettings.json文件,双击打开,然后添加数据库连接字符串。文件中的配置代码如下。
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"BookContext": "Server=.\\sqlexpress;Database=CustomDB;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"AllowedHosts": "*"
}
九、 添加控制器
1) 在Visual Studio 2017中的“解决方案资源管理器”中右键单击 Controllers 文件夹。在弹出菜单中选择 添加 > 新建项。如下图。

2) 在“添加新项-BookApi”对话框中,选择“Web”—>“API 控制器类”模板,并在“名称”输入框中输入 BookController,然后选择“添加”按钮。如下图。

3) 在Visual Studio 2017中打开BookController.cs文件中添加以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BookApi.Models;
using Microsoft.AspNetCore.Mvc; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace BookApi.Controllers
{ [Route("api/[controller]")]
[ApiController]
public class BookController : Controller
{ private readonly BookContext _context; public BookController(BookContext context)
{ _context = context; if (_context.Book.Count() == )
{ context.Book.AddRange(
new Book
{ Name = "Python编程 从入门到实践",
ReleaseDate = DateTime.Parse("2018-1-12"),
Author = "埃里克·马瑟斯",
Price = 75.99M,
Publishing = "机械出版社"
}, new Book
{ Name = "Java编程的逻辑",
ReleaseDate = DateTime.Parse("2018-1-13"),
Author = "马俊昌",
Price = 48.50M,
Publishing = "机械出版社"
}, new Book
{ Name = "统计思维:大数据时代瞬间洞察因果的关键技能",
ReleaseDate = DateTime.Parse("2017-12-23"),
Author = "西内启",
Price = 39.00M,
Publishing = "清华出版社"
}, new Book
{ Name = "微信营销",
ReleaseDate = DateTime.Parse("2018-01-05"),
Author = "徐林海",
Price = 36.90M,
Publishing = "清华出版社"
}, new Book
{ Name = "Java 8实战",
ReleaseDate = DateTime.Parse("2016-04-05"),
Author = "厄马",
Price = 65.60M,
Publishing = "科技出版社"
}
);
_context.SaveChanges(); }
} }
}
对于上面的代码的说明:
1) 定义了没有方法的 API 控制器类。
2) 使用 [ApiController] 属性修饰类。 此属性指示控制器响应 Web API 请求。
从 ASP.NET Core 2.1 开始,使用 [ApiController] 特性修饰控制器类时,将启用操作参数绑定源推理。复杂类型参数通过请求正文自动绑定。 因此,不会使用 [FromBody] 特性对前面操作中的 Book 参数进行显示批注。在 ASP.NET Core 2.2 或更高版本中,可将 [ApiController] 特性应用于程序集。 以这种方式进行注释,会将 web API 行为应用到程序集中的所有控制器。 请注意,无法针对单个控制器执行选择退出操作。
[ApiController] 特性通常结合 Controller 来为控制器启用特定于 REST 行为。 通过 Controllere 可使用NotFound 和 File 等方法。
另一种方法是创建使用 [ApiController] 特性进行批注的自定义基本控制器类:
[ApiController]
public class MyBaseController
{
}
3) 使用 DI 将数据库上下文 (BookContext) 注入到控制器中。 数据库上下文将在控制器中的每个 CRUD 方法中使用。
4) 如果数据库为空,则将几条书籍信息数据添加到数据库。 此代码位于构造函数中,因此在每次出现新 HTTP 请求时运行。 如果删除所有项,则构造函数会在下次调用 API 方法时再次创建。 因此删除可能看上去不起作用,不过实际上确实有效。
使用 ASP.NET Core MVC 创建 Web API(二)的更多相关文章
- 使用 ASP.NET Core MVC 创建 Web API(五)
使用 ASP.NET Core MVC 创建 Web API 使用 ASP.NET Core MVC 创建 Web API(一) 使用 ASP.NET Core MVC 创建 Web API(二) 使 ...
- 使用 ASP.NET Core MVC 创建 Web API(三)
使用 ASP.NET Core MVC 创建 Web API 使用 ASP.NET Core MVC 创建 Web API(一) 使用 ASP.NET Core MVC 创建 Web API(二) 十 ...
- 使用 ASP.NET Core MVC 创建 Web API(四)
使用 ASP.NET Core MVC 创建 Web API 使用 ASP.NET Core MVC 创建 Web API(一) 使用 ASP.NET Core MVC 创建 Web API(二) 使 ...
- 使用 ASP.NET Core MVC 创建 Web API——响应数据的内容协商(七)
使用 ASP.NET Core MVC 创建 Web API 使用 ASP.NET Core MVC 创建 Web API(一) 使用 ASP.NET Core MVC 创建 Web API(二) 使 ...
- 使用 ASP.NET Core MVC 创建 Web API(六)
使用 ASP.NET Core MVC 创建 Web API 使用 ASP.NET Core MVC 创建 Web API(一) 使用 ASP.NET Core MVC 创建 Web API(二) 使 ...
- 使用 ASP.NET Core MVC 创建 Web API(一)
从今天开始来学习如何在 ASP.NET Core 中构建 Web API 以及每项功能的最佳适用场景.关于此次示例的数据库创建请参考<学习ASP.NET Core Razor 编程系列一> ...
- 使用.Net Core MVC创建Web API
创建.Net Core MVC 打开appsettings.json文件,添加数据库连接 { "Logging": { "LogLevel": { " ...
- 002.Create a web API with ASP.NET Core MVC and Visual Studio for Windows -- 【在windows上用vs与asp.net core mvc 创建一个 web api 程序】
Create a web API with ASP.NET Core MVC and Visual Studio for Windows 在windows上用vs与asp.net core mvc 创 ...
- 为什么 web 开发人员需要迁移到. NET Core, 并使用 ASP.NET Core MVC 构建 web 和 webservice/API
2018 .NET开发者调查报告: .NET Core 是怎么样的状态,这里我们看到了还有非常多的.net开发人员还在观望,本文给大家一个建议.这仅代表我的个人意见, 我有充分的理由推荐.net 程序 ...
随机推荐
- php一些需要注意的点
1,类的自动加载: spl_autoload_register(function ($class_name) { require_once $class_name . '.php';}); autol ...
- MySQL 大表优化方案
当MySQL单表记录数过大时,增删改查性能都会急剧下降,可以参考以下步骤来优化: 单表优化 除非单表数据未来会一直不断上涨,否则不要一开始就考虑拆分,拆分会带来逻辑.部署.运维的各种复杂度,一般以整型 ...
- C++11标准中常用到的各种算法汇总.
在C++11标准中定义了很多算法,这些算法可以让我们很方便的操作各种容器和数组,这里要注意一下,这些算法操作的并非容器,而是迭代器,然后通过迭代器来操作容器中的数据,算法本身并不会关注容器中保存的数据 ...
- 【BZOJ 4010】 [HNOI2015]菜肴制作
Description 知名美食家小 A被邀请至ATM 大酒店,为其品评菜肴. ATM 酒店为小 A 准备了 N 道菜肴,酒店按照为菜肴预估的质量从高到低给予1到N的顺序编号,预估质量最高的菜肴编号为 ...
- 快照(Snapshot)技术发展综述
快照(Snapshot)技术发展综述 刘爱贵 摘要:传统数据备份技术存在备份窗口.恢复时间目标RTO和恢复时间点RPO过长的问题,无法满足企业关键性业务的数据保护需求,因此产生了数据快照技术.本文对快 ...
- Angularjs interceptor
angularJs 请求过滤 新建一个服务, $HttpProvider 中有一个 interceptore 数组,所谓的拦截器就是一个注册到该数组的工厂,该工厂在app.config() 中注入, ...
- CentOS7系统操作httpd服务 - 开机启动/重启/查看状态
第一.启动.终止.重启 systemctl start httpd.service #启动 systemctl stop httpd.service #停止 systemctl restart htt ...
- Windows上安装配置SSH教程(2)——在Windows XP和Windows 10上安装并配置OpenSSH for Windows
知识点汇总:http://www.cnblogs.com/feipeng8848/p/8559803.html ------------------------ 安装方式有3种: (1)Windows ...
- 前端性能优化 —— 添加Expires头与Cache-control区别
要:添加Expires头能有效的利用浏览器的缓存能力来改善页面的性能,能在后续的页面中有效避免很多不必要的Http请求,WEB服务器使用Expires头来告诉Web客户端它可以使用一个组件的当前副本, ...
- 如何定义开发完成?(Definition of Done)
最近在拜读郑晔的10x程序员工作法,收益良多,文中提出一个概念叫DoD(Definition of Done)给我的感触颇深.这让我联想到实际工作过程中,经常遇到的扯皮.争吵等各种场景,其实就和这个D ...