.net 客户端开发 “粗体验”

一、背景

最近有个.net 的 sdk的开发功能 ,将之前java 开发的迁移进去…好久没有写 c# 这个玩意,大学也没有类似的经历,而且是mac 环境 开发起来不是很舒畅,快捷键不是很熟悉…

开发工具

下载开发工具: https://docs.microsoft.com/zh-cn/visualstudio/mac/installation?view=vsmac-2019

在这里插入图片描述

包管理

NuGet
在这里插入图片描述

第一个功能就是要使用http 的客户端,如何加入进来的问题 :
http 客户端: https://www.nuget.org/packages/Microsoft.Net.Http/

二、解决问题

2.1 Http 请求客户端 Microsoft.Net.Http

google c# http client : https://stackoverflow.com/questions/23585919/send-json-via-post-in-c-sharp-and-receive-the-json-returned
在这里找到了… http客户端 还有例子 分享的精神非常不错哦!

语法糖不是很关心异步 await 和 Java 还是蛮像的!

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    public class HttpUtil
    {


        //  发送http请求 
        public static async Task<String> PostUrlAsync(string url, string stringPayload, double timeoutMilliseconds)
        {
            using (HttpClient client = new HttpClient())
            {
                if (Double.IsPositiveInfinity(timeoutMilliseconds))
                {
                    client.Timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
                }
                else
                {
                    client.Timeout = TimeSpan.FromMinutes(10);
                }

                
                var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

                using (HttpResponseMessage response = await client.PostAsync(url, httpContent))
                {
                 
                    return await response.Content.ReadAsStringAsync();

                }
            }

        }
    }
}

Task<string> result = HttpUtil.PostUrlAsync(url, requestStr, timeout);
responseJson = result.Result.ToString();

2.2 json 客户端一样 Newtonsoft.Json

https://www.newtonsoft.com/json 都可以在 包管理中直接搜索
和 Java 语法类似 这里也有泛型的 Type 这种概念,通过type 转换 为json。

using System;
using Newtonsoft.Json;

namespace Test
{
    // // json 工具类封装
    public class JSON
    {
        public JSON()
        {
        }

        // 对象转换为 json 
        public static String ToJSONString(Object data)
        {
            var setting = new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };

            return JsonConvert.SerializeObject(data, Formatting.None, setting);
        }


        // json string 转换为 对象
        public static T ParseObject<T>(String text)
        {
            return JsonConvert.DeserializeObject<T>(text);
        }

        // json  string 根据type 转换为 对象 
        public static T ParseObject<T>(String text, Type type)
        {
            return (T)JsonConvert.DeserializeObject(text, type);
        }
    }
}

2.3 泛型的写法问题

  • 限定 参数

https://zhidao.baidu.com/question/1301884451169679939.html
https://stackoverflow.com/questions/557340/how-to-get-the-type-of-t-from-a-member-of-a-generic-class-or-method
https://blog.csdn.net/yanfeng918/article/details/29826511

// 泛型的写法问题 
 public static T Execute<T>(BaseRequest<T> requet) where T : BaseResponse

通过传入的request 直接获取 response 然后进行限定

  • 父类 子类 获取 泛型的type
using System;
namespace Test
{
    public abstract class BaseRequest<T> where T : BaseResponse
    {
        private Type typeT;

        public BaseRequest()
        {
            //获取 泛型的类型
            Type type = this.GetType();
            TypeT = type.BaseType.GetGenericArguments()[0];
        }

        public Type TypeT { get => typeT; set => typeT = value; }

        public abstract String GetApiPath();

    }
}
using System;
namespace Test
{
    public class HelloRequest : BaseRequest<HelloResponse>
    {
        public HelloRequest()
        {
        }

        public override string GetApiPath()
        {
            return "/api/test";
        }
    }
}


using System;
namespace Test
{
    public class BaseResponse
    {
        private String message;

        public BaseResponse()
        {
        }

        public string Message { get => message; set => message = value; }
    }
}

using System;
namespace Test
{
    public class HelloResponse : BaseResponse
    {
        private String helloPass;

        public HelloResponse()
        {
        }

        public string HelloPass { get => helloPass; set => helloPass = value; }
    }
}

  • 泛型的实例化

T reponse = (T)Activator.CreateInstance(typeof(T));

using System;
using Test;
using Newtonsoft.Json;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            HelloRequest helloRequest = new HelloRequest();
            HelloResponse helloResponse = Execute(helloRequest);
            
        }

        // 泛型的写法问题 
        public static T Execute<T>(BaseRequest<T> requet) where T : BaseResponse
        {
            T reponse = (T)Activator.CreateInstance(typeof(T));
            reponse.Message = "error";

            if (true)
            {
                // http请求;
                var responseStr = "";

                reponse = (T)JsonConvert.DeserializeObject(responseStr, requet.TypeT);
                reponse.Message = "ok";
            }
           
            return reponse;
        }
    }
}

2.4 调试 .net 打包的 dll

调试打包的dll 有问题无法debug ,可以 将那个源文件 引入到 当前工程 不进行复制过来,这样就可以愉快的debug了。

三、整体解决问题

一个requeset 对应一个 Response,通过request 直接返回 Response,requeset 构造参数、安全处理、http请求、返回值构造实例化字段信息,方便使用。整体上看和Java 差不多,使用感觉还是Java 好啊,用多了。。。估计 。 新的东西、新的思考,用了1day 搞定了这些问题 感觉还不错。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值