首页 > 编程语言 >C# abp框架Http辅助类

C# abp框架Http辅助类

时间:2023-04-25 18:22:32浏览次数:36  
标签:Http C# request dic abp url using var new

一、定义接口

为什么要定义接口而不直接使用静态类,因为接口可以注入缓存对象,这样就能从缓存中读取指定的请求头

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;

namespace Test.Common
{
    /// <summary>
    /// HTTP请求接口
    /// </summary>
    public interface IHttpClientUtils: IApplicationService
    {
        /// <summary>
        /// 发送HTTP请求,注意Get请求第4个参数才是缓存key,因此第3个参数请设置为null
        /// </summary>
        /// <param name="method">HttpMethod.Get、HttpMethod.Post、HttpMethod.Put、HttpMethod.Delete</param>
        /// <param name="url">完整地址</param>
        /// <param name="model">请求体对象</param>
        /// <param name="cacheKey">鉴权请求头缓存key</param>
        /// <param name="headers">请求头</param>
        /// <returns></returns>
        Task<T> SendAsync<T>(HttpMethod method, string url, object model = null, string cacheKey = "", Dictionary<string, string> headers = null);


        /// <summary>
        /// 发送HTTP表单请求
        /// </summary>
        /// <param name="method">HttpMethod.Post、HttpMethod.Put</param>
        /// <param name="url">完整地址</param>
        /// <param name="model">请求体对象</param>
        /// <param name="cacheKey">鉴权请求头缓存key</param>
        /// <param name="headers">请求头</param>
        /// <returns></returns>
        Task<T> SendFormAsync<T>(HttpMethod method, string url, object model, string cacheKey = "", Dictionary<string, string> headers = null);
    }
}

二、实现接口

1、支持https

2、支持从缓存读取鉴权请求头

3、支持对象携带文件上传

using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Caching;
using Volo.Abp.Json;

namespace Test.Common
{
    /// <summary>
    /// HTTP请求实现
    /// </summary>
    public class HttpClientUtils: ApplicationService, IHttpClientUtils
    {
        private readonly ILogger<HttpClientUtils> _logger;
        private readonly IDistributedCache<Dictionary<string, string>> _cache;
        public HttpClientUtils(
            ILogger<HttpClientUtils> logger,
            IDistributedCache<Dictionary<string, string>> cache) 
        {
            _cache = cache;
            _logger = logger;
        }

        /// <summary>
        /// 发送HTTP请求
        /// </summary>
        /// <param name="method">HttpMethod.Get、HttpMethod.Post、HttpMethod.Put、HttpMethod.Delete</param>
        /// <param name="url">完整地址</param>
        /// <param name="model">请求体对象</param>
        /// <param name="cacheKey">鉴权请求头缓存key</param>
        /// <param name="headers">请求头</param>
        /// <returns></returns>
        public async Task<T> SendAsync<T>(HttpMethod method, string url, object model = null, string cacheKey = "", Dictionary<string, string> headers = null)
        {
            _logger.LogInformation($"SendAsync {method.Method} url = {url}, cacheKey = {cacheKey}, data = {JsonConvert.SerializeObject(model)}");
            try
            {
                using (var client = new HttpClient())
                {
                    if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    { 
                        url = $"http://{url}";
                    }
                    using (var request = new HttpRequestMessage(method, url))    
                    {
                        if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                        {
                            SetHttps();
                        }

                        var sc = new StreamContent(new MemoryStream());
                        if (model != null)
                        {
                            var jsonStr = JsonConvert.SerializeObject(model);
                            var bytes = Encoding.UTF8.GetBytes(jsonStr);
                            sc = new StreamContent(new MemoryStream(bytes));
                        }

                        HeaderHandler(request, sc.Headers, "application/json", headers, cacheKey);

                        request.Content = sc;
                        var rsp = await client.SendAsync(request);
                        return ResponseHandler<T>(rsp);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogError($"SendAsync {method.Method} 请求:{url}, 错误消息:{e.Message}, 请求参数:{JsonConvert.SerializeObject(model)}");
                throw new Exception($"请求HTTP服务{new Uri(url).AbsolutePath}异常:{e.Message}");
            }
        }

        
        /// <summary>
        /// 发送HTTP表单请求
        /// </summary>
        /// <param name="method">HttpMethod.Post、HttpMethod.Put</param>
        /// <param name="url">完整地址</param>
        /// <param name="model">请求体对象</param>
        /// <param name="cacheKey">鉴权请求头缓存key</param>
        /// <param name="headers">请求头</param>
        /// <returns></returns>
        public async Task<T> SendFormAsync<T>(HttpMethod method, string url, object model, string cacheKey = "", Dictionary<string, string> headers = null)
        {
            _logger.LogInformation($"SendFormAsync {method.Method} url = {url}, cacheKey = {cacheKey}, data = {JsonConvert.SerializeObject(model)}");
            try
            {
                var client = new RestClient();
                var request = new RestRequest(url, Method.POST);
                if (method == HttpMethod.Put)
                {
                    request.Method = Method.PUT;
                }
                
                SetHeader(request, cacheKey, headers);
                request.AlwaysMultipartFormData = true;

                var props = model.GetType().GetProperties();
                foreach (var item in props)
                {
                    var k = item.Name;
                    var v = item.GetValue(model);

                    if (v == null)
                    {
                        _logger.LogInformation($"SendFormAsync {method.Method} url = {url} {k} value is null");
                        continue;
                    }

                    if (v.GetType().Name == "Dictionary`2") // 文件只支持字典类型
                    {
                        if (v is Dictionary<string, byte[]>) 
                        {
                            var files = v as Dictionary<string, byte[]>;
                            foreach (var obj in files) // 多个文件只能一个个添加,不能集合到List中
                            {
                                string ext = Path.GetExtension(obj.Key);
                                ext = ext.RemovePreFix(".");

                                _logger.LogInformation($"SendFormAsync file key = {k}, name = {obj.Key}, ext = {ext}, size = {obj.Value.Length}");

                                request.AddFileBytes(k, obj.Value, obj.Key, $"image/{ext}");
                            }
                        }
                    }
                    else
                    {
                        request.AddParameter(k, v);
                    }
                }

                var response = await client.ExecuteAsync(request);
                if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
                {
                    _logger.LogError($"SendFormAsync {method.Method} {url} 响应失败: {response.Content}");
                    throw new Exception($"服务器响应失败:status = {response.StatusCode}");
                }

                _logger.LogInformation($"SendFormAsync {method.Method} {url} Response: {response.Content}");

                return JsonConvert.DeserializeObject<T>(response.Content, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
            }
            catch (Exception e)
            {
                _logger.LogError($"SendFormAsync {method.Method} 请求:{url}, 错误消息:{e.Message}, 请求参数:{JsonConvert.SerializeObject(model)}");
                throw new Exception($"请求HTTP服务{new Uri(url).AbsolutePath}异常:{e.Message}");
            }
        }

        /// <summary>
        /// 设置请求头
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cacheKey"></param>
        private void SetHeader(RestRequest request, string cacheKey, Dictionary<string, string> headers)
        {
            // 鉴权请求头
            var cacheHeaders = _cache.Get(cacheKey);
            if (cacheHeaders != null)
            {
                foreach (var dic in cacheHeaders)
                {
                    _logger.LogInformation($"SetHeader cache header: {dic.Key} = {dic.Value}");

                    if (dic.Key.Equals("authorization", StringComparison.OrdinalIgnoreCase))
                    {
                        request.AddHeader("Authorization", dic.Value);
                    }
                    else
                    {
                        request.AddHeader(dic.Key, dic.Value);
                    }
                }
            }

            // 默认请求头
            if (headers != null && headers.Count > 0)
            {
                foreach (var dic in headers)
                {
                    request.AddHeader(dic.Key, dic.Value);
                }
            }
        }

        /// <summary>
        /// 处理请求头
        /// </summary>
        /// <param name="request">new HttpRequestMessage</param>
        /// <param name="contentHeader">new MultipartFormDataContent</param>
        /// <param name="contentType">multipart/form-data</param>
        /// <param name="headers">Dictionary<string, string></param>
        /// <param name="cacheKey">authorization</param>
        private void HeaderHandler(HttpRequestMessage request, HttpContentHeaders contentHeader, string contentType, Dictionary<string, string> headers, string cacheKey)
        {
            // 添加默认请求头
            if (headers != null && headers.ContainsKey("Content-Type"))
            {
                contentType = headers["Content-Type"];
            }

            if (string.IsNullOrEmpty(contentType)) 
            {
                contentType = "application/json"; // 默认application/json
            }

            _logger.LogInformation($"HeaderHandler {request.Method.Method} {request.RequestUri.AbsolutePath} default contentType header: {contentType}");

            if (contentType.IndexOf("multipart/form-data") != -1)
            {
                contentHeader.Remove("Content-Type"); // MediaTypeHeaderValue不支持解析boundary,所以先删除再Add
                contentHeader.TryAddWithoutValidation("Content-Type", contentType);
            }
            else
            {
                contentHeader.ContentType = new MediaTypeHeaderValue(contentType); 
            }

            // 添加鉴权请求头
            var cacheHeaders = _cache.Get(cacheKey);
            if (cacheHeaders != null)
            {
                foreach (var dic in cacheHeaders)
                {
                    _logger.LogInformation($"HeaderHandler {request.Method.Method} {request.RequestUri.AbsolutePath} cache header: {dic.Key} = {dic.Value}");

                    if (dic.Key.Equals("authorization", StringComparison.OrdinalIgnoreCase))
                    {
                        request.Headers.Authorization = new AuthenticationHeaderValue(dic.Value);
                        // request.SetBearerToken(dic.Value); // 这个方法里加了前缀Bearer,针对接口不同
                    }
                    else
                    {
                        contentHeader.Add(dic.Key, dic.Value); // cookie、token ...
                    }
                }
            }

            // 添加参数请求头
            if (headers != null && headers.Count > 0)
            {
                foreach (var dic in headers)
                {
                    if (contentHeader.ContentType.MediaType == dic.Value)
                    {
                        continue;
                    }
                    contentHeader.Add(dic.Key, dic.Value);
                }
            }
        }

        /// <summary>
        /// 处理HTTP响应
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="rsp"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private T ResponseHandler<T>(HttpResponseMessage rsp)
        {
            if (rsp.StatusCode != HttpStatusCode.OK && rsp.StatusCode != HttpStatusCode.Created)
            {
                _logger.LogError($"ResponseHandler {rsp.RequestMessage.Method.Method} {rsp.RequestMessage.RequestUri.AbsoluteUri} 响应失败: {rsp.Content.ReadAsStringAsync().Result}");
                throw new Exception($"服务器响应失败:status = {rsp.StatusCode}");
            }

            if (rsp is T)
            {
               return (T)(object)rsp;  // 返回HttpResponseMessage,用于获取响应头
            }
            else
            {
                var json = rsp.Content.ReadAsStringAsync().Result;
                _logger.LogInformation($"ResponseHandler {rsp.RequestMessage.Method.Method} {rsp.RequestMessage.RequestUri.AbsoluteUri} 响应:{json}");
                return JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
                // return rsp.Content.ReadFromJsonAsync<T>().Result; // 会检查int null类型报错
            }
        }

        /// <summary>
        /// 设置HTTPS
        /// </summary>
        private void SetHttps()
        {
            // set remote certificate Validation auto pass
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteCertificateValidate);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            // FIX:修复不同.Net版对一些SecurityProtocolType枚举支持情况不一致导致编译失败等问题,这里统一使用数值
            //ServicePointManager.SecurityProtocol = (SecurityProtocolType)48 | (SecurityProtocolType)3072 | (SecurityProtocolType)768 | (SecurityProtocolType)192;
        }

        /// <summary>
        /// 远程证书验证
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="cert"></param>
        /// <param name="chain"></param>
        /// <param name="error"></param>
        /// <returns>验证是否通过,始终通过</returns>
        private bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            return true;
        }
    }
}

三、遇到问题

1、无法添加请求头content-type

var s = new HttpRequestMessage()
s.Headers.Add("Content-Type", "")
报错:Misused header name, 'Content-Type'. Make sure request headers are used with HttpRequestMessage,

var b = new HttpContentHeader()
b.Add("Content-Type", "")
报错:Cannot add value because header 'Content-Type' does not support multiple values.

var b = new HttpContentHeader()
b.ContentType = new MediaTypeHeaderValue("multipart/form-data; boundary=----8db27a5c21ea4f8");
报错:The format of value 'multipart/form-data; boundary=----8db27a5c21ea4f8' is invalid
报错:'multipart/form-data; ----8db27a507065123' is invalid
报错:'multipart/form-data; boundary=--8db27ca4cfafb57' is invalid

1、解决方案:

请看方法:HeaderHandler

 

标签:Http,C#,request,dic,abp,url,using,var,new
From: https://www.cnblogs.com/fanyang1/p/17353486.html

相关文章

  • Linux common clock framework(1)_概述
    1.前言commonclockframework是用来管理系统clock资源的子系统,根据职能,可分为三个部分:1)向其它driver提供操作clocks的通用API。2)实现clock控制的通用逻辑,这部分和硬件无关。3)将和硬件相关的clock控制逻辑封装成操作函数集,交由底层的platform开发者实现,由通用逻辑调用。因此......
  • 2022CSP游记
    目录CSP-J20227:458:158:278:389:129:2310:3411:57中午CSP-S20222:274:156:12估分普及提高自查出分废物鸭子菜菜菜CSP-J2022废了7:45跟随校车到了考场,纪中考点不给矿泉水可还行老朋友都见到了LJHDZRLAFZWTWTCZHWYWJ....WTC已经是ISIJ的金牌了,当年我还跟他是一个......
  • 百度首页静态展示页面HTML+CSS
    一直觉得百度首页很复杂的,有那么多的东西,跟这个博主学习了之后,仿写了一下,样式好像很简单只设置的一些组件的高度而已,不得不说,CSS真是个好东西呀话不多说,直接上代码<!DOCTYPEhtml><htmllang="en"><head><metacharset="utf-8"><title>百度首页</titl......
  • c++遍历搜索关键字
    #include<iostream>#include<windows.h>#include<string.h>#include<strsafe.h>#defineMAX_INPUT_LENGTH255usingnamespacestd;voidprintMemory(char*location,longsize){ printf("\n\n---------------------location......
  • spring mvc3.2 requestbody json显示原理
    1,publicinterfaceHandlerMethodReturnValueHandler{ /** *Whetherthegiven{@linkplainMethodParametermethodreturntype}is *supportedbythishandler. * *@paramreturnTypethemethodreturntypetocheck *@return{@codetrue}ifthis......
  • spring mvc3.2启动分析
    1,GenericServletpublicvoidinit(ServletConfigconfig)throwsServletException{ this.config=config; this.init();}2,HttpServletBean publicfinalvoidinit()throwsServletException{ if(logger.isDebugEnabled()){ logger.debug("......
  • CI Plus简介
    CIPlus简介CIPlus是数字电视机顶盒(STB)和电视(TV)中常用的一种条件接入机制。它通过智能卡(smartcard)对接收机进行认证和授权,使其能接收加密的付费电视节目信号。CIPlus由法国的数字电视行业协会DVB开发,已成为数字电视ConditionalAccess的标准机制,广泛应用于欧洲、中......
  • EasyCVR视频融合平台黑名单功能更新,防止设备恶意注册平台
    为了防止别人恶意注册国标设备,EasyCVR视频融合平台也具备拦截设备注册的功能,即通过国标设备ID和注册IP地址进行拦截,也就是黑名单功能。在3.1版本之前,黑名单的设置是在配置中心—平台接入中,在输入框中添加黑名单ID和黑名单IP,再添加多个和查找已添加的黑名单,是十分困难的,也很不合理。......
  • Easy-Captche的绘画方法
    EasyCaptche功能有5个验证码类型,分别为png类型jpg类型中文类型中文jpg类型算数类型这5个对象中都会有graphicsImage()方法,其功能是将内容画出来。效果展示:绘画方法:在画板上一点一点画//以下方法,为SpecCaptcha中的out方法体privatebooleangraphicsImage(cha......
  • Django框架——路由分发、名称空间、虚拟环境、视图层三板斧、JsonResponse对象、requ
    路由分发#Django支持每个应用都可以有自己独立的路由层、静态文件、模版层。基于该特性多人开发项目就可以完全解耦合,之后利用路由分发还可以整合到一起多个应用都有很多路由与视图函数的对应关系这个时候可以拆分到各自的路由层中使用路由分发之前总路由直接是路由与视图......