AgileHttp在.Net Core中如何实现优化?

摘要:2020年新年将至,先预祝.Net Core越来越好。 做了这么多年一线开发,经常跟Http打交道。比如调用三方的Webservice,比如集成微信支付的时候服务端发起Prepay支付。特别是现在分布式、微服务大行其道,服务间通讯都离不开h
2020年新年将至,先预祝.Net Core越来越好。 做了这么多年一线开发,经常跟Http打交道。比如调用三方的Webservice,比如集成微信支付的时候服务端发起Prepay支付。特别是现在分布式、微服务大行其道,服务间通讯都离不开http调用。 多年前也造过几个http client的小轮子。这次使用C#强大的扩展方法进行了重构,使代码看起来有那么一点流式编程的风格,再配合dynamic有点写JavaScript的赶脚呢。今天拿出来分享给大家,为.Net Core的生态尽一点绵薄之力。 Github: https://github.com/kklldog/AgileHttp 欢迎star 。 安装 Install-Package AgileHttp 示例 使用HTTP.Send方法 使用HTTP.Send / HTTP.SendAsync方法可以直接发送一个请求 HTTP.Send("http://www.baidu.com") // 默认为Get方法 HTTP.Send("http://www.baidu.com", "POST") HTTP.Send("http://www.baidu.com", "POST", new { name = "mjzhou" }) HTTP.Send("http://www.baidu.com", "POST", new { name = "mjzhou" }, new RequestOptions { ContentType = "application/json" }) ResponseInfo response = HTTP.Send("http://localhost:5000/api/user/1"); string content = response.GetResponseContent(); //获取http响应返回值的文本内容 HTTP.SendAsync方法是HTTP.Send方法的异步版本 使用HttpClient类 如果不喜欢手写"GET","POST","PUT"等HTTP方法,可以是使用HttpClient类。HttpClient类内置了GET,POST,PUT,DELETE,OPTIONS几个常用的方法。 var client = new HttpClient("http://www.baidu.com"); client.Get();//使用HttpClient发送Get请求 var client = new HttpClient("http://www.baidu.com"); client.Config(new RequestOptions { ContentType = "application/json" }); client.Post(new { name = "mjzhou" }); //使用HttpClient发送Post请求 ResponseInfo response = new HttpClient("http://localhost:5000/api/user/1").Get(); string content = response.GetResponseContent(); //获取http响应返回值的文本内容 User user1 = new HttpClient("http://localhost:5000/api/user/1").Get<User>(); //泛型方法可以直接反序列化成对象。 Get,Post等方法都有异步版本GetAsync,PostAsync 使用扩展方法 C#强大的扩展方法可以让写代码行云流水。AgileHttp提供了几个扩展方法,让使用更人性化。
阅读全文