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

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

Demo 说明

该项目是基于 .NET Core 2.2Console 控制台实现简单的 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>

image.png

数据交互响应模型: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 bool Success { get; set; }
 
        /// <summary>
        /// 提示信息
        /// </summary>
        public string Msg { get; set; }
 
        /// <summary>
        /// 数据包(jsonString)
        /// </summary>
        public object Data { get; set; }
    }
}

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";
    }
}

封装简易 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
    }
}

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】文件,点击下载;

目录
相关文章
|
5月前
|
Go
在golang中发起http请求以获取访问域名的ip地址实例(使用net, httptrace库)
这只是追踪我们的行程的简单方法,不过希望你跟着探险家的脚步,即使是在互联网的隧道中,也可以找到你想去的地方。接下来就是你的探险之旅了,祝你好运!
246 26
|
10月前
|
开发框架 .NET 开发者
简化 ASP.NET Core 依赖注入(DI)注册-Scrutor
Scrutor 是一个简化 ASP.NET Core 应用程序中依赖注入(DI)注册过程的开源库,支持自动扫描和注册服务。通过简单的配置,开发者可以轻松地从指定程序集中筛选、注册服务,并设置其生命周期,同时支持服务装饰等高级功能。适用于大型项目,提高代码的可维护性和简洁性。仓库地址:&lt;https://github.com/khellang/Scrutor&gt;
248 5
|
5月前
|
JSON 安全 网络协议
HTTP/HTTPS协议(请求响应模型、状态码)
本文简要介绍了HTTP与HTTPS协议的基础知识。HTTP是一种无状态的超文本传输协议,基于TCP/IP,常用80端口,通过请求-响应模型实现客户端与服务器间的通信;HTTPS为HTTP的安全版本,基于SSL/TLS加密技术,使用443端口,确保数据传输的安全性。文中还详细描述了HTTP请求方法(如GET、POST)、请求与响应头字段、状态码分类及意义,并对比了两者在请求-响应模型中的安全性差异。
496 20
|
存储 开发框架 JSON
ASP.NET Core OData 9 正式发布
【10月更文挑战第8天】Microsoft 在 2024 年 8 月 30 日宣布推出 ASP.NET Core OData 9,此版本与 .NET 8 的 OData 库保持一致,改进了数据编码以符合 OData 规范,并放弃了对旧版 .NET Framework 的支持,仅支持 .NET 8 及更高版本。新版本引入了更快的 JSON 编写器 `System.Text.UTF8JsonWriter`,优化了内存使用和序列化速度。
242 0
|
11月前
|
开发框架 .NET C#
在 ASP.NET Core 中创建 gRPC 客户端和服务器
本文介绍了如何使用 gRPC 框架搭建一个简单的“Hello World”示例。首先创建了一个名为 GrpcDemo 的解决方案,其中包含一个 gRPC 服务端项目 GrpcServer 和一个客户端项目 GrpcClient。服务端通过定义 `greeter.proto` 文件中的服务和消息类型,实现了一个简单的问候服务 `GreeterService`。客户端则通过 gRPC 客户端库连接到服务端并调用其 `SayHello` 方法,展示了 gRPC 在 C# 中的基本使用方法。
223 5
在 ASP.NET Core 中创建 gRPC 客户端和服务器
|
10月前
|
开发框架 算法 中间件
ASP.NET Core 中的速率限制中间件
在ASP.NET Core中,速率限制中间件用于控制客户端请求速率,防止服务器过载并提高安全性。通过`AddRateLimiter`注册服务,并配置不同策略如固定窗口、滑动窗口、令牌桶和并发限制。这些策略可在全局、控制器或动作级别应用,支持自定义响应处理。使用中间件`UseRateLimiter`启用限流功能,并可通过属性禁用特定控制器或动作的限流。这有助于有效保护API免受滥用和过载。 欢迎关注我的公众号:Net分享 (239字符)
202 1
|
10月前
|
JSON 数据格式
.net HTTP请求类封装
`HttpRequestHelper` 是一个用于简化 HTTP 请求的辅助类,支持发送 GET 和 POST 请求。它使用 `HttpClient` 发起请求,并通过 `Newtonsoft.Json` 处理 JSON 数据。示例展示了如何使用该类发送请求并处理响应。注意事项包括:简单的错误处理、需安装 `Newtonsoft.Json` 依赖,以及建议重用 `HttpClient` 实例以优化性能。
259 2
|
10月前
|
开发框架 缓存 .NET
GraphQL 与 ASP.NET Core 集成:从入门到精通
本文详细介绍了如何在ASP.NET Core中集成GraphQL,包括安装必要的NuGet包、创建GraphQL Schema、配置GraphQL服务等步骤。同时,文章还探讨了常见问题及其解决方法,如处理复杂查询、错误处理、性能优化和实现认证授权等,旨在帮助开发者构建灵活且高效的API。
266 3
|
11月前
|
安全 API 网络安全
使用OkHttp进行HTTPS请求的Kotlin实现
使用OkHttp进行HTTPS请求的Kotlin实现
|
开发框架 监控 前端开发
在 ASP.NET Core Web API 中使用操作筛选器统一处理通用操作
【9月更文挑战第27天】操作筛选器是ASP.NET Core MVC和Web API中的一种过滤器,可在操作方法执行前后运行代码,适用于日志记录、性能监控和验证等场景。通过实现`IActionFilter`接口的`OnActionExecuting`和`OnActionExecuted`方法,可以统一处理日志、验证及异常。创建并注册自定义筛选器类,能提升代码的可维护性和复用性。
189 3

热门文章

最新文章