基于.NET Core 2.2 的 Console 控制台实现简单 HTTP 请求的【CRUD】操作

1. Demo 说明:该项目是基于 .NET Core 2.2 的 Console 控制台实现简单的 http 模拟请求,对应http谓词实现的CRUD的封装操作;本项目依赖的 NuGet 包:Microsoft.AspNetCore.Http.Abstractions;Newtonsoft.Json;RestSharp;

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
    <PackageReference Include="RestSharp" Version="106.6.10" />
  </ItemGroup>

</Project>

2. 数据交互响应模型:ResponseModel

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApi
{
    /// <summary>
    /// 公共响应模型
    /// </summary>
    public sealed class ResponseModel
    {
        /// <summary>
        /// 响应码
        /// </summary>
        public int Code { get; set; }

        /// <summary>
        /// 提示信息
        /// </summary>
        public string Msg { get; set; }

        /// <summary>
        /// 数据包(jsonString)
        /// </summary>
        public object Data { get; set; }
    }
}

3. API 参数配置模型:ApiConfigModel

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApi
{
    /// <summary>
    /// api 配置模型
    /// </summary>
    public class ApiConfigModel
    {
        /// <summary>
        /// api地址
        /// </summary>
        public string HostAddress { get; set; }

        /// <summary>
        /// 客户端访问类型
        /// </summary>
        public string ContentType { get; set; } = "PC";

        /// <summary>
        /// 访问账号
        /// </summary>
        public string Account { get; set; }

        /// <summary>
        /// Token
        /// </summary>
        public string Token { get; set; }

        /// <summary>
        /// 报文数据发送类型
        /// </summary>
        public string ClientType { get; set; } = "application/json";

        /// <summary>
        /// api版本号
        /// </summary>
        public string Version { get; set; } = "v1";
    }
}

4. 封装简易Http-API助手:SimpleHttpApiHelper

using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApi
{
    /// <summary>
    /// 简易Http-API助手
    /// </summary>
    public class SimpleHttpApiHelper
    {
        #region 单例模式
        //创建私有化静态obj锁  
        private static readonly object _ObjLock = new object();
        //创建私有静态字段,接收类的实例化对象  
        private static SimpleHttpApiHelper _SimpleHttpApiHelper = null;
        //构造函数私有化  
        private SimpleHttpApiHelper() { }
        //创建单利对象资源并返回  
        public static SimpleHttpApiHelper GetSingleObj()
        {
            if (_SimpleHttpApiHelper == null)
            {
                lock (_ObjLock)
                {
                    if (_SimpleHttpApiHelper == null)
                    {
                        _SimpleHttpApiHelper = new SimpleHttpApiHelper();
                    }
                }
            }
            return _SimpleHttpApiHelper;
        }
        #endregion

        #region 参数配置
        private static string _HostAddress;
        private static string _ContentType;
        private static string _Account;
        private static string _Token;
        private static string _ClientType;
        private static string _Version;

        /// <summary>
        /// 初始化参数配置项
        /// </summary>
        /// <param name="hostAddress">api地址</param>
        /// <param name="account">访问账号</param>
        /// <param name="token">Token</param>
        /// <param name="contentType">报文数据发送类型</param>
        /// <param name="clientType">客户端访问类型</param>
        /// <param name="version">api版本号</param>
        public void SetApiConfig(string hostAddress, string account, string token, string contentType = "application/json", string clientType = "PC", string version = "v1")
        {
            if (string.IsNullOrWhiteSpace(hostAddress) || string.IsNullOrWhiteSpace(account) || string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(contentType))
                throw new NullReferenceException("参数空异常!");
            else if (!account.Contains("|"))
                throw new FormatException("Account约定格式异常!");

            _HostAddress = hostAddress;
            _ContentType = contentType;
            _Account = account;
            _Token = token;
            _ClientType = clientType;
            _Version = version;
        }

        /// <summary>
        /// 初始化参数配置项
        /// </summary>
        /// <param name="model"></param>
        public void SetApiConfig(ApiConfigModel model)
        {
            if (string.IsNullOrWhiteSpace(model.HostAddress) || string.IsNullOrWhiteSpace(model.Account) || string.IsNullOrWhiteSpace(model.Token) || string.IsNullOrWhiteSpace(model.ContentType))
                throw new NullReferenceException("参数空异常!");
            else if (!model.Account.Contains("|"))
                throw new FormatException("Account约定格式异常!");

            _HostAddress = model.HostAddress;
            _ContentType = model.ContentType;
            _Account = model.Account;
            _Token = model.Token;
            _ClientType = model.ClientType;
            _Version = model.Version;
        }
        #endregion

        #region 实现HTTP的【CRUD】操作
        public enum HttpMethod { GET, POST, PUT, DELETE };
        private string GetHttpMethod(HttpMethod httpMethod)
        {
            string _HttpMethod = string.Empty;
            switch (httpMethod)
            {
                case HttpMethod.GET:
                    _HttpMethod = "GET";
                    break;
                case HttpMethod.POST:
                    _HttpMethod = "POST";
                    break;
                case HttpMethod.PUT:
                    _HttpMethod = "PUT";
                    break;
                case HttpMethod.DELETE:
                    _HttpMethod = "DELETE";
                    break;
            }
            return _HttpMethod;
        }

        /// <summary>
        /// HttpWebRequest 方式实现【CRUD】
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="httpMethod"></param>
        /// <param name="controller"></param>
        /// <param name="actionCode"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public T CreateHttpWebRequest<T>(HttpMethod httpMethod, string controller, string actionCode, string postDataStr = "")
        {
            string apiUrl = $"{_HostAddress}/{_Version}/{controller}/{actionCode}";
            var request = WebRequest.Create(apiUrl + (string.IsNullOrWhiteSpace(postDataStr) ? "" : "?") + postDataStr) as HttpWebRequest;
            request.Method = GetHttpMethod(httpMethod);
            request.ContentType = _ContentType; //"text/html;charset=UTF-8";
            request.Headers["Account"] = _Account;
            request.Headers["Token"] = _Token;
            request.Headers["ClientType"] = _ClientType;

            string jsonString = string.Empty;
            var response = request.GetResponse() as HttpWebResponse;
            using (Stream myResponseStream = response.GetResponseStream())
            {
                using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("UTF-8")))
                {
                    Task<string> task = myStreamReader.ReadToEndAsync();
                    jsonString = task.Result;
                    //myStreamReader.Close();
                    //myResponseStream.Close();
                }
            }
            if (string.IsNullOrWhiteSpace(jsonString))
                return default;
            else
                return JsonConvert.DeserializeObject<T>(jsonString);
        }

        /// <summary>
        /// WebClient 方式实现【CRUD】
        /// </summary>
        /// <param name="method"></param>
        /// <param name="controller"></param>
        /// <param name="actionCode"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public JsonObject CreateWebClientRequest(HttpMethod httpMethod, string controller, string actionCode, JsonObject data)
        {
            string apiUrl = $"{_HostAddress}/{_Version}/{controller}/{actionCode}";
            string jsonData = data == null ? string.Empty : data.ToString(); //请求参数
            string jsonString = null; //响应数据
            using (WebClient wc = new WebClient())
            {
                wc.Headers["Content-Type"] = _ContentType;//"application/x-www-form-urlencoded";
                wc.Headers["Account"] = _Account;
                wc.Headers["Token"] = _Token;
                wc.Headers["ClientType"] = _ClientType;
                wc.Encoding = Encoding.UTF8;
                Task<string> task = wc.UploadStringTaskAsync(apiUrl, GetHttpMethod(httpMethod), jsonData);
                jsonString = task.Result;
            }
            if (string.IsNullOrWhiteSpace(jsonString))
                return new JsonObject();
            else
                return JsonConvert.DeserializeObject<JsonObject>(jsonString);
        }

        #endregion
        /// <summary>
        ///  异常捕获器
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <typeparam name="T3"></typeparam>
        /// <typeparam name="T4"></typeparam>
        /// <typeparam name="TR"></typeparam>
        /// <param name="func"></param>
        /// <param name="t1"></param>
        /// <param name="t2"></param>
        /// <param name="t3"></param>
        /// <param name="t4"></param>
        /// <returns></returns>
        public static TR ExceptionTrapper<T1,T2,T3,T4,TR>(Func<T1, T2, T3, T4, TR> func, T1 t1, T2 t2, T3 t3, T4 t4) 
        {
            try
            {
               return func(t1,t2,t3,t4);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        #region 简化封装-委托调用
        public T HttpWebRequest<T>(HttpMethod httpMethod, string controller, string actionCode, string postDataStr = "")
        {
            return ExceptionTrapper(CreateHttpWebRequest<T>, httpMethod, controller, actionCode, postDataStr);
        }

        public JsonObject HttpWebRequest(HttpMethod httpMethod, string controller, string actionCode, JsonObject data)
        {
            return ExceptionTrapper(CreateWebClientRequest, httpMethod, controller, actionCode, data);
        } 
        #endregion
    }
}

5. Console 控制台调用:

using RestSharp;
using System;
using System.Collections.Generic;

namespace ConsoleApi
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello http!");

            //1.配置注册(重载实现)
            string hostAddress = "http://192.168.10.231:9003/api"; //此处写约定格式的api地址
            string account = "666|xxx";
            string token = "token";
            //SimpleHttpApiHelper.GetSingleObj().SetApiConfig(hostAddress, account, token); //参数方式
            SimpleHttpApiHelper.GetSingleObj().SetApiConfig(new ApiConfigModel { HostAddress= hostAddress, Account= account, Token = token }); //模型方式

            //2.原生调用(未添加异常捕获)
            var json = SimpleHttpApiHelper.GetSingleObj().CreateHttpWebRequest<ResponseModel>(SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);
            var jsonObj = SimpleHttpApiHelper.GetSingleObj().CreateWebClientRequest(SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);

            //3.委托调用(添加异常捕获)
            var s1 = SimpleHttpApiHelper.ExceptionTrapper<SimpleHttpApiHelper.HttpMethod, string, string, JsonObject, JsonObject>(SimpleHttpApiHelper.GetSingleObj().CreateWebClientRequest, SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);
            var s2 = SimpleHttpApiHelper.ExceptionTrapper<SimpleHttpApiHelper.HttpMethod, string, string, string, ResponseModel>(SimpleHttpApiHelper.GetSingleObj().CreateHttpWebRequest<ResponseModel>, SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);

            //4.简化封装-委托调用(添加异常捕获)
            var s3 = SimpleHttpApiHelper.GetSingleObj().HttpWebRequest<string>(SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);
            var s4 = SimpleHttpApiHelper.GetSingleObj().HttpWebRequest(SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);

            Console.ReadKey();
        }
    }
}

以上简单示例完毕,Demo 链接:https://download.csdn.net/my/uploads 选择 【ConsoleApi.zip】文件,点击下载;

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ChaITSimpleLove

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值