首页 > 其他分享 >.net core读取leancloud上的数据

.net core读取leancloud上的数据

时间:2023-07-11 10:47:24浏览次数:49  
标签:core heads string url request response leancloud null net


.net core读取leancloud上的数据


    public IActionResult Index()
    {
        try
        {
            string url = "https://xxxx.xxx.net/1.1/classes/guestbook?order=-createdAt&count=1";  
            string leancloud_appid = "dJzCJfdsfdsoHsz";
            string leancloud_appkey = "eggw223fdsWr2u2vNFxv";

            Dictionary<string, string> heads = new Dictionary<string, string>();
            heads.Add("X-LC-Id", leancloud_appid);
            heads.Add("X-LC-Key", leancloud_appkey);

            string retstr = Util.HttpService.Get(url, heads);

            Model.GuestBook_LeanReturn retm = Newtonsoft.Json.JsonConvert.DeserializeObject<Model.GuestBook_LeanReturn>(retstr);
            ViewBag.totalcount = retm.count;


            return View(retm.results);
        }
        catch (Exception ex)
        {
            return Content("出错:"+ex.Message);
        }
    }

  

 

 

using System;
namespace Niunan.Admin.Model
{
	public class GuestBook_LeanReturn
	{
        public List<GuestBook_LeanReturnInner> results { set; get; }
        public int count { set; get; }
    }

    public class GuestBook_LeanReturnInner { 
        public string lianxi { set; get; } 
        public string body { set; get; }
        public DateTime createdAt { set; get; } 
        public string objectId { set; get; }
    }
}

  


 

 

用的rest api的方法来查数据的,具体可查官方文档   

https://docs.leancloud.cn/sdk/storage/guide/rest/

分页的话可以在url里加上&limit=10&sikp=5

工具类的代码如下:

 

using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace Niunan.Admin.Util
{
	public class HttpService
	{
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认,否则打不开    
            return true;
        }

        /// <summary>
        /// post提交
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="url"></param>
        /// <param name="isUseCert"></param>
        /// <param name="timeout"></param>
        /// <param name="contenttype">如:application/x-www-form-urlencoded,text/xml</param>
        /// <param name="heads">头信息</param>
        /// <returns></returns>
        public static string Post(string xml, string url, bool isUseCert, int timeout, string contenttype = "application/x-www-form-urlencoded", Dictionary<string, string> heads = null)
        {
            System.GC.Collect();//垃圾回收,回收没有正常关闭的http连接

            string result = "";//返回结果

            System.Net.HttpWebRequest request = null;
            System.Net.HttpWebResponse response = null;
            Stream reqStream = null;

            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = "POST";
                request.Timeout = timeout * 1000;

                if (heads != null)
                {
                    foreach (var item in heads.Keys)
                    {
                        request.Headers.Add(item, heads[item]);
                    }
                }

                //设置代理服务器
                //WebProxy proxy = new WebProxy();                          //定义一个网关对象
                //proxy.Address = new Uri(WxPayConfig.PROXY_URL);              //网关服务器端口:端口
                //request.Proxy = proxy;

                //设置POST的数据类型和长度
                request.ContentType = contenttype;
                byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
                request.ContentLength = data.Length;

                //是否使用证书
                if (isUseCert)
                {
                    //复制微信DEMO的,这里不用证书
                    //string path = HttpContext.Current.Request.PhysicalApplicationPath;
                    //X509Certificate2 cert = new X509Certificate2(path + WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD);
                    //request.ClientCertificates.Add(cert);
                    //Log.Debug("WxPayApi", "PostXml used cert");
                }

                //往服务器写入数据
                reqStream = request.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();

                //获取服务端返回
                response = (HttpWebResponse)request.GetResponse();

                //获取服务端返回数据
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (Exception e)
            {
                // Log.Error("HttpService", e.ToString());
                throw e;
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }

        /// <summary>
        /// 处理http GET请求,返回数据
        /// </summary>
        /// <param name="url">请求的url地址</param>
        /// <returns>http GET成功后返回的数据,失败抛WebException异常</returns>
        public static string Get(string url, Dictionary<string, string> heads = null)
        {
            System.GC.Collect();
            string result = "";

            System.Net.HttpWebRequest request = null;
            System.Net.HttpWebResponse response = null;

            //请求url以获取数据
            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = "GET";

                if (heads != null)
                {
                    foreach (var item in heads.Keys)
                    {
                        request.Headers.Add(item, heads[item]);
                    }
                }

                //设置代理
                //WebProxy proxy = new WebProxy();
                //proxy.Address = new Uri(WxPayConfig.PROXY_URL);
                //request.Proxy = proxy;

                //获取服务器返回
                response = (HttpWebResponse)request.GetResponse();

                //获取HTTP返回数据
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (Exception e)
            {

                throw e;
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }

        /// <summary>
        /// http里的delete方式
        /// </summary>
        /// <param name="url"></param>
        /// <param name="heads"></param>
        /// <returns></returns>
        public static string Delete(string url, Dictionary<string, string> heads = null)
        {
            System.GC.Collect();
            string result = "";

            HttpWebRequest request = null;
            HttpWebResponse response = null;

            //请求url以获取数据
            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = "DELETE";

                if (heads != null)
                {
                    foreach (var item in heads.Keys)
                    {
                        request.Headers.Add(item, heads[item]);
                    }
                }

                //设置代理
                //WebProxy proxy = new WebProxy();
                //proxy.Address = new Uri(WxPayConfig.PROXY_URL);
                //request.Proxy = proxy;

                //获取服务器返回
                response = (HttpWebResponse)request.GetResponse();

                //获取HTTP返回数据
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (Exception e)
            {

                throw e;
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }
    }
}

 

 

  


标签:core,heads,string,url,request,response,leancloud,null,net
From: https://www.cnblogs.com/niunan/p/17543345.html

相关文章

  • Vue3+.net6.0 三 响应式基础,methods
    这里的示例都用选项式风格在Vue3中,数据是基于 JavaScriptProxy(代理) 实现响应式的。这个示例中输出是false,因为当你在赋值后再访问 this.someObj,此值已经是原来的 newObj 的一个响应式代理。需要注意的是newObj 并不会变成响应式。<scripttype="module">const......
  • .NET周刊【7月第2期 2023-07-09】
    由于这周比较忙,只给出了标题和链接,没有具体的简介。另外根据粉丝朋友的反馈,".NET周报"更名为".NET周刊",希望大家喜欢:)国内文章......
  • Kubernets与Docker的故事
    在2016年底的1.5版里,Kubernetes引入了一个新的接口标准:CRI,ContainerRuntimeInterface。CRI采用了ProtoBuffer和gPRC,规定kubelet该如何调用容器运行时去管理容器和镜像,但这是一套全新的接口,和之前的Docker调用完全不兼容。 Kubernetes也只能同时提供一个“折中”......
  • aspnetcore 中间件执行顺序
    这是用例和返回结果输出的结果是对称的当我第一眼看着这个操作时满脑子不解:一个方法是怎么扳成2截来使用的要是我来做肯定让用户传2个委托完整实现代码classProgram{staticList<Action<Action>>middlewareList=newList<Action<Action>>();staticvoidUse(......
  • aardio桌面软件开发 简单,打包后文件小,支持 .net python 和 众多插件
    aardio编程语言-官网 aardio ......
  • .NET Core应用程序每次启动后使用string.GetHashCode()方法获取到的哈希值(hash)不相
    前言如标题所述,在ASP.NETCore应用程序中,使用string.GetHashCode()方法去获取字符串的哈希值,但每次重启这个ASP.NETCore应用程序之后,同样的字符串的哈希值(hash)但不相同了。这是什么意思呢?具体的应用场景是这样的:项目中有一张表的某个字段保存了类似URL这样的字符串,这张表......
  • PROFINET转ETHERCAT协议网关ethercat总线伺服如何控制
    捷米特JM–ECAT-PN是自主研发的一款PROFINET从站功能的通讯网关。该产品主要功能是将PROFINET网络和ETHERCAT网络连接起来。捷米特JM-ECAT-PN连接到PROFINET总线中做为从站使用,连接到ETHERCAT总线中做为从站使用。 3.技术参数PROFINET技术参数网关做为PROFINET......
  • ETHERNET/IP转PROFIBUS-DP网关PROFIBUS DP/ EtherNet IP网关
    大家好,今天要给大家介绍一款非常神奇的通讯网关捷米特JM-DPM-EIP!这款产品可以将各种PROFIBUS-DP从站接入到ETHERNET/IP网络中,真是一款神奇的产品啊!你是否想过,如果没有这款产品,PROFIBUS-DP从站和ETHERNET/IP网络之间该怎么通讯呢?让我们来看看这款产品到底有哪些神奇之处吧! 这款......
  • .NET写一个自己的Lambda表达式与表达式树
    LambdaExpression继承ExpressionExpression又继承LambdaExpressio所以,Expression与Expression的区别在于:泛型类以静态类型的方法标识了它是什么种类的表达式,也就是说,他确定了返回类型和参数。所以显然,TDelegate必须是一个委托类型。注意:并非所有的Lambda表达式都能转......
  • .Net Core Jwt鉴权授权
    目录简介基于.NetCore验证方式Jwt获取Token引入三方包生成TokenUserInfoJwtConfigWebApi测试(获取Token)Program.csappsetting.jsonController.NetCore验证(webApi)ProgarmContorller.NetCore授权简介Program.csJwtAuthorization.cs注意Autofac注册授权服务Controller注意......