使用.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 ...
随机推荐
- Oracle中的锁
Oracle中的锁 锁是一种机制,多个事务同时访问一个数据库对象时,该机制可以实现对并发的控制 按照用户系统锁可以分为自动锁和显示锁. 自动锁(系统上锁):DML锁.DDL锁.systemlocks锁 ...
- BZOJ3832: [Poi2014]Rally(拓扑排序 堆)
题意 题目链接 Sol 最直观的思路是求出删除每个点后的最长路,我们考虑这玩意儿怎么求 设\(f[i]\)表示以\(i\)结尾的最长路长度,\(g[i]\)表示以\(i\)开始的最长路长度 根据DAG ...
- Ubuntu OpenJDK + Tomcat7 的安装
jdk1.7.0安装首先安装openjdk,安装命令如下图. 安装好之后检查jdk文件路径,如下图. 建立链接(ls),如下图. 成功之后,配置环境变量,并重新运行一下,如下图. 环境变量在文件最后面 ...
- 导航栏布局时遇到的问题以及解决办法 css选择器优先级
得到的导航栏效果 添加#menu ul li{width:30px;} 效果如图 将会使列表项和分隔区域的宽度同时改变因为id选择器的优先级高于类选择器,此时应该为列表项添加内联样式如图 才能得到如下 ...
- CentOS 6.x 安装vnc
https://www.cnblogs.com/pipci/p/7833581.html 1.安装vnc server [root@pxe ~]# yum install tigervnc-ser ...
- Action 中获取表单数据的三种方式
(尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/53138905 冷血之心的博客) Action 中获取表单提交数据 ...
- vue项目部署上线
前言 今天把自己写的demo登录写完了,就想着试着走一下部署上线的流程.参考了很多的文档,终于成功进行了部署.在这里将服务器的搭建和vue项目的 部署上线进行整理(都是基础的知识,希望对大家有帮助.对 ...
- Dos命令删除添加新服务
安装服务sc create Svnservice binpath= "d:\subversion\bin\svnserve.exe --service -r E:\projectversio ...
- svn回退到具体的版本
svn回退到具体的版本 找到项目的版本号 命令行中输入相关命令 到指定地点找到项目即可
- 屏蔽响应事件继续向父视图传递的category
屏蔽响应事件继续向父视图传递的category 这篇教程是上一篇教程的升级版,将复杂的代码封装成了category,更便于使用:) 效果: 源码: UIGestureRecognizer+EnvetI ...