使用.Net Core MVC创建Web API
创建.Net Core MVC

打开appsettings.json文件,添加数据库连接
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
//添加数据库连接
"ConnectionStrings": {
"BookContext": "Server=.;Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"AllowedHosts": "*"
}
数据库的准备工作,创建表贴出SQL:
CREATE TABLE [dbo].[Book](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Author] [nvarchar](max) NULL,
[Name] [nvarchar](50) NOT NULL,
[Price] [decimal](18, 2) NOT NULL,
[ReleaseDate] [datetime2](7) NOT NULL,
[Publishing] [nvarchar](max) NOT NULL,
[RowVersion] [timestamp] NULL,
CONSTRAINT [PK_Book] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
创建数据上下文BookContext
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; }
}
}
注册数据库上下文,打开Startup.cs
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_1);
}
// 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();
}
}
}
创建实体类Book.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace BookApi.Models
{
public class Book
{
public int ID { get; set; }
[Required]
[StringLength(50, MinimumLength = 2)]
public string Name { get; set; }
[Display(Name = "出版日期")]
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
[Range(1, 200)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }
public string Author { get; set; }
[Required]
public string Publishing { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
}
创建控制器类,BookController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BookApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
// 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() == 0)
{
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();
}
}
// GET: api/Book
[HttpGet]
public async Task<ActionResult<IEnumerable<Book>>> GetBookItems()
{
return await _context.Book.ToListAsync();
}
// GET: api/Book/5
[HttpGet("{id}")]
public async Task<ActionResult<Book>> GetBookItem(int id)
{
var bookItem = await _context.Book.FindAsync(id);
if (bookItem == null)
{
return NotFound();
}
return bookItem;
}
// POST: api/Book
[HttpPost]
public async Task<ActionResult<Book>> PostBookItem(Book item)
{
_context.Book.Add(item);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetBookItem), new { id = item.ID }, item);
}
}
}
运行项目,使用firefox RESTer调用接口请求数据


使用.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(一) 六.添加数据库上下文 数据库上下文是使用Entity Framewor ...
- 使用 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 编程系列一> ...
- 温故知新,使用ASP.NET Core创建Web API,永远第一次
ASP.NET Core简介 ASP.NET Core是一个跨平台的高性能开源框架,用于生成启用云且连接Internet的新式应用. 使用ASP.NET Core,您可以: 生成Web应用和服务.物联 ...
- 【翻译】在Visual Studio中使用Asp.Net Core MVC创建你的第一个Web API应用(一)
HTTP is not just for serving up web pages. It's also a powerful platform for building APIs that expo ...
随机推荐
- 阿里云服务器被他人通过SSH暴力破解后的安全加固
背景说明:我登录阿里云服务器控制台时,收到几条安全警告信息. 从图中可以知道,对方的IP地址是47.97.68.118,通过SSH登录方式,登录时用我服务器里的admin用户,然后用穷举法暴力破解ad ...
- 在GDI+中如何实现以左下角为原点的笛卡尔坐标系
今天写了一个求点集合的凸包的一个算法,虽然结果求解出来了,但是想将过程用GDI+绘制出来,就需要将点绘制出来,然而c#GDI+中绘图的坐标与我们常用数学中笛卡尔坐标系是不一样的,所以就要转换GDI+中 ...
- CSS样式之a标签(原文网址http://www.divcss5.com/shili/s57.shtml)
这是个人在做网站的时候整理的关于a标签的使用方法,整理一下,方便下次使用. 一.a超链接的代码 <a href="http://www.baidu.com" target=& ...
- Ubuntu搜索不到WiFi的解决办法
时间:2018年1月25日 废话连篇:杭州下了第一场雪,冒险严寒来到实验室,打开电脑,纳尼连不上wifi了,好吧!不要被这件小事影响心情,开始修复了,经过一顿搜索,可能是因为驱动的问题,终端输入以下两 ...
- (项目积累的)SQL数据库点滴
最近的的系统用的数据库是mssql,软件mssql 2008 r2 1.存储过程:后勤的综合管理系统(后端内网访问)三层架构配套用的是存储过程,里面列表展示的都是用存储过程,如下: 1)数据库脚本 U ...
- flutter开发中常用的dart插件
flutter插件官网地址:https://pub.dartlang.org/packages/ 1. image_picker 一个可以从图库选择图片,并可以用相机拍摄新照片的flutter插件 2 ...
- CVE-2017-17215 - 华为HG532命令注入漏洞分析
前言 前面几天国外有个公司发布了该漏洞的详情.入手的二手 hg532 到货了,分析测试一下. 固件地址:https://ia601506.us.archive.org/22/items/RouterH ...
- mysql 日期时间类型
datetime timestamp year date time drop table test;create table test (dt datetime, ts timestamp, y ye ...
- OpenLDAP权限配置
安装好了openldap之后,就是对它进行配置了,其中一项就是设置访问控制,限制普通用户只能修改/访问他们能修改/访问的项.这就是ACL需要做的事情. 设置方法 1.可以将 include行放在/et ...
- Oracle AP更新供应商
/*l_return_status:S l_msg_count:0 l_msg_data: l_vendor_id:133003 l_party_id:236055 */ DECLARE l_ ...