unity通过WebAPI调用MongoDB

1.unity模块-调用WebAPI:

 1 using UnityEngine;
 2 using System.Collections;
 3 using System.IO;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Net; 
 7  
 8 public class LoadMongoDB : MonoBehaviour
 9 { 
10     public string url;
11     void Start()
12     {    
13          if (string.IsNullOrEmpty(url))
14          {
15               url = "http://localhost:23544/ActionApi/UserInfo/CreatMongoDB?MongoClient_DB_Name=mongodb://ip(mongodb库的连接ip和端口),MyMongoDB,BsonDocumentName";
16          }
17     }
18     void Update()
19     { 
20         if (Input.GetKeyDown(KeyCode.P))
21         {  
22             string str = HttpPost(url, "");
23             Debug.Log(str);
24         }
25     }
26     public static string HttpPost(string url, string body)
27     {  
28         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
29         request.Method = "POST"; 
30 
31         byte[] buffer = System.Text.Encoding.UTF8.GetBytes(body);
32         request.ContentLength = buffer.Length;
33         request.GetRequestStream().Write(buffer, 0, buffer.Length);
34         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
35         using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
36         {
37             return reader.ReadToEnd();
38         }
39     }
40 }    

2.WebAPI模块-Web API 路由定义:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Net.Http;
 5 using System.Web.Http;
 6 using Microsoft.Owin.Security.OAuth;
 7 using Newtonsoft.Json.Serialization;
 8 
 9 namespace WebAPI_Mongo
10 {
11     public static class WebApiConfig
12     {
13         public static void Register(HttpConfiguration config)
14         {
15             // Web API 配置和服务
16             // 将 Web API 配置为仅使用不记名令牌身份验证。
17             config.SuppressDefaultHostAuthentication();
18             config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
19 
20             // Web API 路由
21             config.MapHttpAttributeRoutes();
22 
23             //自定义路由:匹配到action
24             config.Routes.MapHttpRoute(
25                 name: "ActionApi",
26                 routeTemplate: "actionapi/{controller}/{action}/{id}",
27                 defaults: new { id = RouteParameter.Optional }
28             );
29         }
30     }
31 }

3.WebAPI模块-调用MongoDB:

 1 using System.Linq;
 2 using System.Net.Http;
 3 using System.Text.RegularExpressions;
 4 using System.Web.Http;
 5 using MongoDB.Bson;
 6 using MongoDB.Driver; 
 7 
 8 namespace WebAPI_Mongo.Controllers
 9 {
10     public class UserInfoController : ApiController
11     {  
12         private ApiTools tool = new ApiTools(); 
13 
14         MongoClient client;
15         IMongoDatabase database;
16         IMongoCollection<BsonDocument> collection; 
17         [HttpPost]
18         public HttpResponseMessage CreatMongoDB(string MongoClient_DB_Name)
19         {
20             //Connection_MongoDB();
21             //增加
22             client = new MongoClient(MongoClient_DB_Name.Split(',')[0]);
23             database = client.GetDatabase(MongoClient_DB_Name.Split(',')[1]);
24             collection = database.GetCollection<BsonDocument>(MongoClient_DB_Name.Split(',')[2]);
25 
26             BsonDocument ls_BsonDocument = new BsonDocument { { "Name", "_萧朗" } };
27             collection.InsertOne(ls_BsonDocument); 
28 
29             return tool.MsgFormat(ResponseCode.成功, "已建立" + MongoClient_DB_Name.Split(',')[2], "true");
30         } 
31     }
32     public class ApiTools
33     {
34         private string msgModel = "{{"code":{0},"message":"{1}","result":{2}}}"; 
35 
36         public HttpResponseMessage MsgFormat(ResponseCode code, string explanation, string result)
37         {
38             string r = @"^(-|+)?d+(.d+)?$";
39             string json = string.Empty;
40             if (Regex.IsMatch(result, r) || result.ToLower() == "true" || result.ToLower() == "false" || result == "[]" || result.Contains('{'))
41             {
42                 json = string.Format(msgModel, (int)code, explanation, result);
43             }
44             else
45             {
46                 if (result.Contains('"'))
47                 {
48                     json = string.Format(msgModel, (int)code, explanation, result);
49                 }
50                 else
51                 {
52                     json = string.Format(msgModel, (int)code, explanation, """ + result + """);
53                 }
54             }
55             return new HttpResponseMessage { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") };
56         }
57     }
58     public enum ResponseCode
59     {
60         失败 = 00000,
61         成功 = 10200,
62     }
63 }
支持个人观看使用,如商用或转载,请告知! -----萧朗(QQ:453929789 Email:xiaolang_xl@sina.com)
原文地址:https://www.cnblogs.com/XiaoLang0/p/13933304.html