• 视频教程:VS Core 40分钟进行WebAPI开发和调用(入门级别)


    本文章是根据 Vance的视频教程《C# .NET Core实现快速Web API开发》编写而来,再加上自己的一些理解。

    视频教程地址::https://www.bilibili.com/video/BV11E411n74a

    GitHub源码:

    https://github.com/BobinYang/NetCoreWebAPI_Demo/

    教程:

    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_str}");
        string result = Post(url, req_str);
        
        Console.WriteLine($"[响应]{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

  • 相关阅读:
    第一篇unity
    C#相关知识小结
    必须知道的八大种排序算法【java实现】
    JAVA八大排序算法
    二进制、八进制、十进制、十六进制之间的转换
    八大排序算法
    JSONArray数据转换成java List
    使用json-lib的JSONObject.toBean( )时碰到的日期属性转换的问题
    一探前端开发中的JS调试技巧
    SpringMVC注解说明
  • 原文地址:https://www.cnblogs.com/springsnow/p/13595167.html
Copyright © 2020-2023  润新知