mongodb集成到asp .net Core Web Api项目(源码可下载)
目录
linux安装mongodb
启动mongodb服务
mongodb集成到asp .net Core Web Api项目(源码可下载)
1.首先我们需要创建一个poems数据库
进入mongodb安装的bin目录
cd /usr/local/mongodb/bin
执行启动命令
./mongod --config /usr/local/mongodb/conf/mongodb.confs
输入mongo命令
[root@iZwz92gauwq11sx9e2qmpeZ bin]# mongo MongoDB shell version v4.0.13 connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb Implicit session: session { "id" : UUID("152de530-65d3-4de1-8cb7-302b3ced501c") } MongoDB server version: 4.0.13c
执行创建poems数据库命令
use poems
由于配置了权限认证,我们需要为poems数据库创建一个用户
但先要切换到admin库,然后输入登录用户进行授权验证
登录成功后,切回到 poems 库,就可以为该库创建用户了,执行命令如下:
> use admin switched to db admin > db.auth('root','123456') 1 > use poems switched to db poems > db.createUser({user:'ptest',pwd:'123456987',roles:['readWrite']}) Successfully added user: { "user" : "ptest", "roles" : [ "readWrite" ] } >
2.创建 ASP.NET Core Web API 项目
创建net Core项目,将其命名为:PoemsApi,创建项目后,通过NuGet库引入MongoDB.Driver包
3.添加实体模型
将 Models 目录添加到项目根。
使用以下代码将 FamousPoemsModels类添加到 Models 目录
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using System; namespace Models { public class FamousPoemsModels { public FamousPoemsModels() { } [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } /// <summary> /// 作者 /// </summary> public string vcAuthor { get; set; } /// <summary> /// 内容 /// </summary> public string vcContent { get; set; } /// <summary> /// 标题 /// </summary> public string vcTitle { get; set; } /// <summary> /// 创建时间 /// </summary> [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime dtCreateTime { get; set; } /// <summary> /// 更新时间 /// </summary> [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime dtUpdateTime { get; set; } } }
4.添加配置模型
(1)、appsettings.json 添加以下数据库配置值
{ "MongdbSettings": { "FamousPoemsCollectionName": "FamousPoems", "ConnectionString": "mongodb://ptest:123456987@120.79.76.160:27017/poems?maxPoolSize=500", "DatabaseName": "poems" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }
(2)、使用以下代码将 MongdbSettings.cs 文件添加到 Services目录 ,Services目录需要先创建,并在根目录下
using System; namespace Service { public class MongdbSettings : IMongdbSettings { public string FamousPoemsCollectionName { get; set; } public string ConnectionString { get; set; } public string DatabaseName { get; set; } } public interface IMongdbSettings { public string FamousPoemsCollectionName { get; set; } string ConnectionString { get; set; } string DatabaseName { get; set; } } }
MongdbSettings类用于存储 appsettings.json 文件的 MongdbSettings 属性值。 JSON 和 C# 具有相同的属性名称,目的是简化映射过程。
5.将以下突出显示的代码添加到 Startup.ConfigureServices
public void ConfigureServices(IServiceCollection services) { #region mongodb配置 services.Configure<MongdbSettings>( Configuration.GetSection(nameof(MongdbSettings))); services.AddSingleton<IMongdbSettings>(sp => sp.GetRequiredService<IOptions<MongdbSettings>>().Value);
#endregion services.AddControllers(); }
appsettings.json 文件的 MongdbSettings部分绑定到的配置实例在依赖关系注入 (DI) 容器中注册。 例如,MongdbSettings对象的 ConnectionString 属性使用 appsettings.json 中的 MongdbSettings:ConnectionString 属性进行填充。
IMongdbSettings 接口使用单一实例服务生存期在 DI 中注册。 在注入时,接口实例时将解析为 MongdbSettings对象。
6.添加 CRUD 操作服务
使用以下代码将 FamousPoemsService类添加到 Services 目录
using Models; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Services { public class FamousPoemsService { private readonly IMongoCollection<FamousPoemsModels> _mongDb; public FamousPoemsService(IMongdbSettings settings) { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); _mongDb = database.GetCollection<FamousPoemsModels>(settings.FamousPoemsCollectionName); } public FamousPoemsModels Insert(FamousPoemsModels model) { _mongDb.InsertOne(model); return model; } public int InsertManyAsync(List<FamousPoemsModels> list) { _mongDb.InsertManyAsync(list); return list.Count; } public void Update(string id, FamousPoemsModels model) { _mongDb.ReplaceOne(m => m.Id == id, model); } public void Delete(FamousPoemsModels model) { _mongDb.DeleteOne(m => m.Id == model.Id); } public FamousPoemsModels Get(string id) { return _mongDb.Find<FamousPoemsModels>(book => book.Id == id).FirstOrDefault(); } public List<FamousPoemsModels> GetPageList(int nPageIndex = 1, int nPageSize = 10) { //设置排序字段 var sort = Builders<FamousPoemsModels>.Sort.Descending(it => it.dtCreateTime); return _mongDb.Find<FamousPoemsModels>(b => true).Sort(sort).Skip((nPageIndex - 1) * nPageSize).Limit(nPageSize).ToList(); } } }
上面的代码通过构造函数注入从 DI 检索IMongdbSettings实例。 使用此方法可访问在添加配置模型部分中添加的 appsettings.json 配置值。
将以下突出显示的代码添加到 Startup.ConfigureServices
public void ConfigureServices(IServiceCollection services) { #region mongodb配置 services.Configure<MongdbSettings>( Configuration.GetSection(nameof(MongdbSettings))); services.AddSingleton<IMongdbSettings>(sp => sp.GetRequiredService<IOptions<MongdbSettings>>().Value); services.AddSingleton<FamousPoemsService>(); #endregion services.AddControllers(); }
上面的代码向 DI 注册了 FamousPoemsService 类,以支持消费类中的构造函数注入。 单一实例服务生存期是最合适的,因为 FamousPoemsService直接依赖于 MongoClient。 根据官方 Mongo Client 重用准则,应使用单一实例服务生存期在 DI 中注册 MongoClient。
FamousPoemsService 类使用以下 MongoDB.Driver 成员对数据库执行 CRUD 操作:
MongoClient:读取用于执行数据库操作的服务器实例。 此类的构造函数提供了 MongoDB 连接字符串
public FamousPoemsService(IMongdbSettings settings) { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); _mongDb = database.GetCollection<FamousPoemsModels>(settings.FamousPoemsCollectionName); }
7.添加控制器
使用以下代码将 PoemsController类添加到 Controllers 目录
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Models; using Newtonsoft.Json; using Services; namespace WebApi.Controllers { public class PoemsController : ControllerBase { private readonly FamousPoemsService _poemsService; public PoemsController(FamousPoemsService poemsService) { _poemsService = poemsService; } [HttpPost("Poems/Insert")] public ActionResult Insert([FromBody]FamousPoemsModels poems) { poems.dtCreateTime = DateTime.Now; poems.dtUpdateTime = DateTime.Now; return Content(JsonConvert.SerializeObject(_poemsService.Insert(poems))); } [HttpPost("Poems/InsertManyAsync")] public ActionResult InsertManyAsync([FromBody]List<FamousPoemsModels> poems) { return Content(JsonConvert.SerializeObject(_poemsService.InsertManyAsync(poems))); } [HttpPost("Poems/Update")] public ActionResult Update([FromBody]FamousPoemsModels poems) { _poemsService.Update(poems); return NoContent(); } [HttpPost("Poems/Delete")] public ActionResult Delete([FromBody]FamousPoemsModels poems) { _poemsService.Delete(poems); return NoContent(); } [HttpGet("Poems/Get")] public ActionResult Get(string id) { return Content(JsonConvert.SerializeObject(_poemsService.Get(id))); } [HttpGet("Poems/List")] public ActionResult GetPageList(int nPageIndex = 1, int nPageSize = 10) { return Content(JsonConvert.SerializeObject(_poemsService.GetPageList(nPageIndex, nPageSize))); } } }
gitee克隆地址:https://gitee.com/fan_zhongtuan/PoemsApi.git
百度网盘链接:https://pan.baidu.com/s/1GGCOfcd3KsUIImiRe68R8g
提取码:1yf5
mongodb客户端工具:https://www.jb51.net/article/199496.htm(Navicat Premium 15 永久破解激活工具及安装教程)