首先下载安装 MongoDB
https://www.mongodb.com/download-center/community
新建数据库
创建WEB API项目
引用MongoDB驱动
https://www.nuget.org/packages/MongoDB.Driver
创建Models文件夹 增加Book类文件
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BooksApi.Models
{
public class Book
{
[BsonId]//指定主键
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("Name")]
public string BookName { get; set; }
[BsonElement("Price")]
public decimal Price { get; set; }
[BsonElement("Category")]
public string Category { get; set; }
[BsonElement("Author")]
public string Author { get; set; }
}
}
创建Services文件夹添加BookService服务类
using BooksApi.Models;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BooksApi.Services
{
public class BookService
{
private readonly IMongoCollection<Book> _books;
public BookService(IConfiguration configuration)
{
//获取操作实例 进行构造注入
var client = new MongoClient(configuration.GetConnectionString("MongoDBConnString"));
var database = client.GetDatabase("DB");
_books = database.GetCollection<Book>("Books");
}
public async Task<Book> Create(Book book)
{
await _books.InsertOneAsync(book);
return book;
}
public async Task<List<Book>> Get()
{
var result= await _books.FindAsync(book=> true);
return result.ToList();
}
public async Task Update(string id, Book bookIn)
{
await _books.ReplaceOneAsync(book => book.Id == id, bookIn);
}
public async Task Remove(Book bookIn)
{
await _books.DeleteOneAsync(book => book.Id == bookIn.Id);
}
public async Task Remove(string id)
{
await _books.DeleteOneAsync(book => book.Id == id);
}
}
}
appsettings.json中配置DB连接字符串
{
"ConnectionStrings": {
"MongoDBConnString": "mongodb://localhost:27017"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
Startup中配置服务注册,否则不能进行依赖注入消费。
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<BookService>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
添加Book控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BooksApi.Models;
using BooksApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BooksApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BooksController : ControllerBase
{
private readonly BookService _bookService;
public BooksController(BookService bookService)
{
_bookService = bookService;
}
public async Task<List<Book>> Get()
{
return await _bookService.Get();
}
public async Task<Book> Create(Book book)
{
return await _bookService.Create(book);
}
//其他方法同理,不一一进行实现。
}
}
安装Swagger进行测试。这里我使用以下Swagger包
https://github.com/RicoSuter/NSwag
具体使用方法文档已经有文字和视频讲解,此处不做说明。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BooksApi.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace BooksApi
{
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.AddScoped<BookService>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSwaggerDocument();--添加SwaggerUI
}
// 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();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUi3();
}
}
}
运行测试