C# 后台POST数据及API接收简记


    背景:项目对接各种卡壳,本地测试处理效果,暂记。

    开发环境:VS 2019 16.4 +NetCore 3.1.1+CoreMVC

    接口为WebApi(Core)

    一、后台请求第三方接口(模拟)

       //参数序列化后直接写入
     public string Posts(string postData, string url) { try { System.Net.ServicePointManager.DefaultConnectionLimit = 50; var postRequest = HttpWebRequest.Create(url) as HttpWebRequest; postRequest.KeepAlive = false; postRequest.Timeout = 5000; postRequest.Method = "POST"; postRequest.ContentType = "application/json;"; postRequest.ContentLength = postData.Length; postRequest.AllowWriteStreamBuffering = false; StreamWriter writer = new StreamWriter(postRequest.GetRequestStream(), Encoding.ASCII); writer.Write(postData); writer.Flush(); HttpWebResponse response = postRequest.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); using (System.IO.StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8"))) { string jsonStr = reader.ReadToEnd(); return jsonStr; } } catch (Exception ex) { _logger.LogInformation("post Error!=" + ex); } return ""; }     /// /// 内容转换为流写入post /// /// /// /// /// public static string PostMoths(string url, string param, Dictionary<string, string> dicHeider = null) { Encoding encod = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Accept = "text/html,application/xhtml+xml,*/*"; request.ContentType = "application/json"; if (dicHeider != null) { foreach (KeyValuePair<string, string> item in dicHeider) { request.Headers.Add(item.Key, item.Value); } } byte[] buffer = encod.GetBytes(param); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length);
using StreamReader reader = new StreamReader(((HttpWebResponse)request.GetResponse()).GetResponseStream(), Encoding.UTF8); return reader.ReadToEnd(); }

  二、接收方:#测试接收    

 [HttpPost]
        [Route("GetAJWSWJ")]
        public async Task GetAJWSWJ(dynamic jsondata)
        {
         try
                {
                    var param = JsonConvert.DeserializeObject(jsondata.ToString());
                    var strParam = param["wsslbh"].ToString();
                    _logger.LogInformation($"接收参数解析!strParam={strParam}");
                    var paramsStr = new { wsslbh = strParam };
                    _logger.LogInformation($"传递参数!strParam={paramsStr}");
                    //var valssss = this.Posts(JsonConvert.SerializeObject(paramsStr), text3);
                    var valssss = this.PostMoths(text3, JsonConvert.SerializeObject(paramsStr));
                    await BodyReturn(JsonConvert.SerializeObject(valssss));
                }
                catch (Exception ex)
                {
                    _logger.LogInformation($"PostMoths Error!" + ex.Message);
                    await BodyReturn(ex.Message);
                }
     }