Asp.net Core1.1创建简单WebAPI对Mongodb进行CRUD操作

1.使用VS2017建立一个.netcore1.1的WebAPI项目

选择webAPI模板

 

2.添加mongodb驱动

工具——NuGet包管理器——程序包管理控制台:

Install-Package MongoDB.Driver

 3.创建对应的接口已经实现类

1.创建mongodb操作帮助类

 1     public class MongoHelper
 2     {
 3         private static readonly IMongoCollection<UserItem> _mycol;
 4 
 5         static MongoHelper()
 6         {
 7             string connectString = "mongodb://127.0.0.1:27017";
 8             string dataBaseName = "test";
 9             string collectionName = "mycol";
10             MongoClient mc = new MongoClient(connectString);
11             _mycol = mc.GetDatabase(dataBaseName).GetCollection<UserItem>(collectionName);
12         }
13 
14 
15         public static void InsertData(UserItem DataS)
16         {
17             _mycol.InsertOne(DataS);
18         }
19 
20         public static bool DeleteData(ObjectId objectId)
21         {
22             var filter = Builders<UserItem>.Filter.Eq("_id", objectId);
23             var result = _mycol.DeleteOne(filter);
24             return result.IsAcknowledged;
25         }
26 
27         public static bool UpdateData(UserItem updataDs)
28         {
29             var filter = Builders<UserItem>.Filter.Eq("_id", updataDs._id);
30             var result = _mycol.ReplaceOne(filter, updataDs);
31             return result.IsAcknowledged;
32         }
33 
34         public static UserItem SearchData(ObjectId objectId)
35         {
36             var filter = Builders<UserItem>.Filter.Eq("_id", objectId);
37             var result = _mycol.Find(filter);
38             return result.FirstOrDefault();
39         }
40 
41         public static List<UserItem> GetAllData()
42         {
43             return _mycol.AsQueryable().ToList();
44         }
45     }
View Code

这里需要在linux主机上建立mongodb服务

因为Mongodb帮助类中需要操作文档模型的对象,这里需要在项目中添加一个文件夹Models,添加一个类UserItem,具体内容如下

 1 namespace MongodbCRUD.Models
 2 {
 3     public class UserItem
 4     {
 5         [JsonConverter(typeof(ObjectIdConverter))]
 6         public ObjectId _id { get; set; }
 7         public string CompanyName { get; set; }
 8         public string ContactName { get; set; }
 9         public string Phone { get; set; }
10     }
11     class ObjectIdConverter : JsonConverter
12     {
13 
14         public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
15         {
16             serializer.Serialize(writer, value.ToString());
17 
18         }
19 
20         public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
21         {
22             if (reader.TokenType != JsonToken.String)
23             {
24                 throw new Exception($"Unexpected token parsing ObjectId. Expected String.get{reader.TokenType}");
25             }
26             var value = (string)reader.Value;
27             return string.IsNullOrEmpty(value) ? ObjectId.Empty : ObjectId.Parse(value);
28         }
29 
30         public override bool CanConvert(Type objectType)
31         {
32             return typeof(ObjectId).IsAssignableFrom(objectType);
33         }
34 
35 
36     }
37 }
View Code

其中添加JsonConverter特性是为了解决mongodb的objectid类型属性转换的问题

2.创建数据库操作接口以及实现类

1     public interface IUserRepository
2     {
3         void Create(UserItem jsString);
4         bool Update(UserItem jsString);
5         bool Delete(string id);
6         List<UserItem> GetAll();
7         UserItem FindOneById(string id);
8     }
View Code
 1 public void Create(UserItem jsString)
 2         {
 3             MongoHelper.InsertData(jsString);
 4         }
 5 
 6         public bool Delete(string id)
 7         {
 8             return MongoHelper.DeleteData(ObjectId.Parse(id));
 9         }
10 
11         public UserItem FindOneById(string id)
12         {
13             return MongoHelper.SearchData(ObjectId.Parse(id));
14         }
15 
16         public List<UserItem> GetAll()
17         {
18             return MongoHelper.GetAllData();
19         }
20 
21         public bool Update(UserItem jsString)
22         {
23             return MongoHelper.UpdateData(jsString);
24         }
View Code

添加一个控制器类:UserController

 1     [Route("api/[controller]")]
 2     public class UserController : Controller
 3     {
 4 
 5         public IUserRepository UserItems { get; set; }
 6 
 7         public UserController(IUserRepository userItems)
 8         {
 9             UserItems = userItems;
10         }
11 
12         public IActionResult GetAll()
13         {
14             return new ObjectResult(MongoHelper.GetAllData());
15         }
16 
17         [HttpGet("{id}")]
18         public IActionResult GetById(string id)
19         {
20 
21             return new ObjectResult(UserItems.FindOneById(id));
22         }
23 
24         [HttpPost]
25         public void Create([FromBody]UserItem item)
26         {
27             UserItems.Create(item);
28         }
29 
30         [HttpPut]
31         public IActionResult Update([FromBody] UserItem data)
32         {
33             var result = UserItems.Update(data);
34             return new ObjectResult(result);
35         }
36 
37         [HttpDelete("{id}")]
38         public IActionResult Delete(string id)
39         {
40             var result = UserItems.Delete(id);
41             return new ObjectResult(result);
42         }
43     }
View Code

3.修改startup.cs文件

注入UserRepository:services.AddSingleton<IUserRepository, UserRepository>();

 1     public class Startup
 2     {
 3         public Startup(IHostingEnvironment env)
 4         {
 5             var builder = new ConfigurationBuilder()
 6                 .SetBasePath(env.ContentRootPath)
 7                 .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
 8                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
 9                 .AddEnvironmentVariables();
10             Configuration = builder.Build();
11         }
12 
13         public IConfigurationRoot Configuration { get; }
14 
15         // This method gets called by the runtime. Use this method to add services to the container.
16         public void ConfigureServices(IServiceCollection services)
17         {
18             // Add framework services.
19             services.AddMvc();
20             services.AddCors(options => {
21                 options.AddPolicy("AllowAll",
22                     builder => {
23                         builder.AllowAnyOrigin()
24                             .AllowAnyMethod()
25                             .AllowAnyHeader()
26                             .AllowCredentials();
27                     });
28             });
29 
30             services.AddSingleton<IUserRepository, UserRepository>();
31         }
32 
33         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
34         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
35         {
36             loggerFactory.AddConsole(Configuration.GetSection("Logging"));
37             loggerFactory.AddDebug();
38             app.UseCors("AllowAll");
39             app.UseMvc();
40         }
41     }
View Code

其中services.AddCors。。。。和Configure方法中的app.UseCors("AllowAll");都是为了解决跨域访问问题

4.部署到debian8

在主机上安装.dotnet core 1.1(TODO:介绍debian8安装dotnet core1.1)

vs——生成——发布——文件夹

将要发布的程序上传到主机的普通用户目录下(TODO:linux新建普通用户,安装ftp并配置ftp服务)

运行命令:dotnet 程序集名称.dll

 

5.使用守护程序保持程序运行

为了让程序一直在主机上保持运行,这里我们安装微软推荐的守护程序:Supervisor(TODO:介绍安装并配置Supervisor)

 

 

项目源码已经上传github:https://github.com/LuckyMars/AliyunWebAPI

 

其中TODO部分会以新的随笔形式详细介绍。

转载于:https://www.cnblogs.com/luckymars/p/7344396.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值