使用.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调用接口请求数据
人说,如果你很想要一样东西,就放它走 。如果它回来找你,那么它永远都是你的。要是它没有回来,那么不用再等了,因为它根本就不是你的。
——伊恩·麦克尤恩