欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net core并发请求发送HttpWebRequest的坑解决

程序员文章站 2022-06-25 08:57:49
在framework中,大量并发 httpwebrequest 需要设置一个最大连接数 servicepointmanager.defaultconnection...

在framework中,大量并发 httpwebrequest 需要设置一个最大连接数

servicepointmanager.defaultconnectionlimit = 200;

但是在.net core中却无效,因为core不使用 servicepointmanager 管理连接数,在core中只有使用httpclient,httpcilentfactory来管理连接数,如果在core中使用 servicepointmanager 不但不起作用,并且大量并发使用 httpwebrequest 会导致 iis 直接假死,所以在core中,只能使用 httpclient 和 httpcilentfactory这一条路可走

在core中的startup注册一个httpclient的名字

    public void configureservices(iservicecollection services)
    {
      services.addhttpclient("httpclientfactorydemo");
    }

然后在controller中创建

using system;
using system.collections.generic;
using system.net.http;
using system.net.http.headers;
using system.text;
using system.threading.tasks;
using system.web;
using microsoft.aspnetcore.mvc;
 
namespace httpclientfactorydemo.controllers
{
  [route("api/[controller]")]
  [apicontroller]
  public class valuescontroller : controllerbase
  {
    private readonly ihttpclientfactory _httpclientfactory;
 
    public valuescontroller(ihttpclientfactory httpclientfactory)
    {
      _httpclientfactory = httpclientfactory;
    }
 
    public static string urlencode(string temp, encoding encoding)
    {
      stringbuilder stringbuilder = new stringbuilder();
      for (int i = 0; i < temp.length; i++)
      {
        string t = temp[i].tostring();
        string k = httputility.urlencode(t, encoding);
        if (t == k)
        {
          stringbuilder.append(t);
        }
        else
        {
          stringbuilder.append(k.toupper());
        }
      }
      return stringbuilder.tostring();
    }
 
    [httpget]
    public async task<actionresult> get()
    {
      encoding.registerprovider(codepagesencodingprovider.instance);
      string xmlcontent = "<?xml version=\"1.0\" encoding=\"gbk\" standalone=\"yes\"?><xml><version>1</version><ins_cd>08a9999999</ins_cd><mchnt_cd>0002900f0370588</mchnt_cd><term_id></term_id><random_str>93b4efa6d0d84808a76355ff0f7a178d</random_str><sign>g1+tbpyevwsqjej9x7zrobrtfti/itujweeyl3at/9xlfd844jv2wb/gnvkuevp890tf1ub+eate1qbyhsu97cpqr6riudxqw2nnjkzbzsg00c1d8070szpf4c1hksufhlr2npn+7dvianlcjrfztgotq/wtcarrl/sjijeaxyg=</sign><order_type>alipay</order_type><goods_des>卡盟测试</goods_des><goods_detail></goods_detail><addn_inf></addn_inf><mchnt_order_no>2018121302054468584629</mchnt_order_no><curr_type></curr_type><order_amt>1</order_amt><term_ip>127.0.0.1</term_ip><txn_begin_ts>20181213020544</txn_begin_ts><goods_tag></goods_tag><auth_code>288232051781304899</auth_code><sence>1</sence><reserved_sub_appid></reserved_sub_appid><reserved_limit_pay></reserved_limit_pay></xml>";
      xmlcontent = urlencode(xmlcontent, encoding.getencoding("gbk"));
 
      dictionary<string, string> nvs = new dictionary<string, string> { { "req", xmlcontent } };
      encoding encoding = encoding.getencoding("gbk");
      stringbuilder buffer = new stringbuilder();
      int i = 0;
      idictionary<string, string> sortedparams = new sorteddictionary<string, string>(nvs);
      foreach (keyvaluepair<string, string> kvp in nvs)
      {
        buffer.appendformat(i > 0 ? "&{0}={1}" : "{0}={1}", kvp.key,
          urlencode(kvp.value, encoding.getencoding("gbk")));
        i++;
      }
      byte[] postbody = encoding.getbytes(buffer.tostring());
 
      var client = _httpclientfactory.createclient("httpclientfactorydemo");
      var request = new httprequestmessage
      {
        requesturi = new uri("https://spay.fuiou.com/commonquery"),
        method = httpmethod.post,
        content = new bytearraycontent(postbody),
      };
 
      request.content.headers.contenttype =
        new mediatypeheadervalue("application/x-www-form-urlencoded");
 
      return ok(await client.sendasync(request));
 
    }
  }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。