基于.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;



  
    Exe
    netcoreapp2.2
  

  
    
    
    
  


基于.NET Core 2.2 的 Console 控制台实现简单 HTTP 请求的【CRUD】操作_第1张图片

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

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

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

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

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

3. API 参数配置模型:ApiConfigModel

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

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

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

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

        /// 
        /// Token
        /// 
        public string Token { get; set; }

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

        /// 
        /// api版本号
        /// 
        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
{
    /// 
    /// 简易Http-API助手
    /// 
    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;

        /// 
        /// 初始化参数配置项
        /// 
        /// api地址
        /// 访问账号
        /// Token
        /// 报文数据发送类型
        /// 客户端访问类型
        /// api版本号
        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;
        }

        /// 
        /// 初始化参数配置项
        /// 
        /// 
        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;
        }

        /// 
        /// HttpWebRequest 方式实现【CRUD】
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public T CreateHttpWebRequest(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 task = myStreamReader.ReadToEndAsync();
                    jsonString = task.Result;
                    //myStreamReader.Close();
                    //myResponseStream.Close();
                }
            }
            if (string.IsNullOrWhiteSpace(jsonString))
                return default;
            else
                return JsonConvert.DeserializeObject(jsonString);
        }

        /// 
        /// WebClient 方式实现【CRUD】
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        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 task = wc.UploadStringTaskAsync(apiUrl, GetHttpMethod(httpMethod), jsonData);
                jsonString = task.Result;
            }
            if (string.IsNullOrWhiteSpace(jsonString))
                return new JsonObject();
            else
                return JsonConvert.DeserializeObject(jsonString);
        }

        #endregion
        /// 
        ///  异常捕获器
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static TR ExceptionTrapper(Func 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(HttpMethod httpMethod, string controller, string actionCode, string postDataStr = "")
        {
            return ExceptionTrapper(CreateHttpWebRequest, 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(SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);
            var jsonObj = SimpleHttpApiHelper.GetSingleObj().CreateWebClientRequest(SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);

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

            //4.简化封装-委托调用(添加异常捕获)
            var s3 = SimpleHttpApiHelper.GetSingleObj().HttpWebRequest(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】文件,点击下载;

你可能感兴趣的:(.NET,Core,跨平台)