C# .NET Core实现快速Web API开发
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-httpswebapi
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

浙公网安备 33010602011771号