C# .NET Core實現快速Web API開發
阿新 • • 發佈:2020-09-16
C# .NET Core實現快速Web API開發
目錄
https://github.com/BobinYang/NetCoreWebAPI_Demo/
視訊地址:https://www.bilibili.com/video/BV11E411n74a
1、介面樣例
{ "ISBN": "2", "name": "1", "price": "1", "date": "20200219", "authors": [ { "name": "Jerry", "sex": "M", "birthday": "18888515" }, { "name": "Tom", "sex": "M", "birthday": "18440101" } ] }
2、服務端:
新建一個目錄:BookManage
建立一個WebAPI專案:
https://docs.microsoft.com/zh-cn/dotnet/core/tools/dotnet-new
dotnet new
--no-https
webapi
Controller :
[ApiController] [Route("book/[controller]")] public class ValuesController : ControllerBase { private static Dictionary<string, AddRequest> DB = new Dictionary<string, AddRequest>(); [HttpPost] public AddResponse Post([FromBody] AddRequest req) { AddResponse resp = new AddResponse(); try { DB.Add(req.ISBN, req); resp.ISBN = req.ISBN; resp.message = "交易成功"; resp.result = "S"; } catch (Exception ex) { Console.Write(ex); resp.ISBN = ""; resp.message = "交易失敗"; resp.result = "F"; } return resp; } }
net core3.1 web api中使用newtonsoft替換掉預設的json序列化元件:
第一步,引入包
https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.NewtonsoftJson
dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
第二步,修改sartups.cs中的 ConfigureServices
using Newtonsoft.Json.Serialization;
public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(options => { // Use the default property (不改變元資料的大小寫) casing options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); }
還有如下的方式:
//修改屬性名稱的序列化方式,首字母小寫 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //修改時間的序列化方式 options.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy/MM/dd HH:mm:ss" });
3、客戶端
新建一個目錄:BookClient
建立一個Console專案:
dotnet new console
新建HTTP請求:
static void Main(string[] args) { Console.WriteLine("Hello World!"); string url = "http://localhost:5000/book/values"; AddRequest req = new AddRequest(); req.ISBN = "2"; req.name = ".NET Core從入門到入土"; req.authors = null; req.price = 1.00M; string req_str = JsonConvert.SerializeObject(req);//序列化成JSON
Console.WriteLine($"[REQ]{req_str}"); string result = Post(url, req_str); Console.WriteLine($"[RESP]{result}"); AddResponse resp = JsonConvert.DeserializeObject<AddResponse>(result);//反序列化 Console.WriteLine($"[resp.result]{resp.result}"); }
static string Post(string url, string req_str) { HttpClient client = new HttpClient(); var content = new StringContent(req_str); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = client.PostAsync(url, content); response.Wait(); response.Result.EnsureSuccessStatusCode(); var res = response.Result.Content.ReadAsStringAsync(); res.Wait(); return res.Result; }
切換到客戶端目錄下,執行程式:
cd BookClient
dotnet runn
如果想學習netcore跨平臺技術,請聯絡我,聯絡方式微信:18700482809 或者qq:454666932