• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

在后端C#中callwebapi

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

我们要想使用web api, 需要首先在azure 中创建application. (如何创建application可以参考我的另一篇blog 从O365中获取users到D365中 )

 

Get

我们可以用JObject 和 JArray 来快速获取而不需要DeserializeObject

         //server-side online oauth2
                var sessionResult = (Opportunity)Session["OpportunityData"];
                var httpUrl = resourceUrl + "api/data/v9.1/accounts?$filter=accountid%20eq%20" + "hello world";
                AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/common", false);
                AuthenticationResult result = authContext.AcquireToken(resourceUrl, clientId, new UserCredential(account, password));
                using (HttpClient httpClient = new HttpClient())
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                    httpClient.Timeout = new TimeSpan(0, 2, 0);  // 2 minutes  
                    httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", result.AccessToken);
                    httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                    httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                    HttpResponseMessage response = httpClient.GetAsync(httpUrl).Result;
                    var returnvalue = response.Content.ReadAsStringAsync().Result;
                    LogHelper.WriteLog("Return value:");
                    LogHelper.WriteLog(returnvalue);
                    JObject jo = JsonConvert.DeserializeObject<JObject>(returnvalue);
                    JArray ja = JsonConvert.DeserializeObject<JArray>(jo["value"].ToString());
          }

 

POST:

ServicePointManager.SecurityProtocol 是必须要添加的. 不然会抛出 security 的exception.

req.Headers.Add("If-Match", "*"); 如果我们在请求的表头里添加了  if-match的话,  如果有相同的record创建时,会抛出 exception 412 error 而不会去创建一条一模一样的数据.

                var weburi = resourceUrl + "api/data/v9.1/accounts";
                AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/common", false);
                AuthenticationResult result = authContext.AcquireToken(resourceUrl, clientId, new UserCredential(account, password));
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(weburi);

                req.Method = "post";
                req.Accept = "application/json";
                req.ContentType = "application/json; charset=utf-8";
                req.Headers.Add("OData-MaxVersion", "4.0");
                req.Headers.Add("OData-Version", "4.0");
req.Headers.Add("If-Match","*"); req.Headers.Set(
"Authorization", "Bearer " + result.AccessToken); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; var newSurveyResult = new JObject(); newSurveyResult.Add("booleanvalue", true); newSurveyResult.Add("stringvalue", "Hello World!");byte[] data = Encoding.UTF8.GetBytes(newSurveyResult.ToString()); Stream newStream = req.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); using (HttpWebResponse res = (HttpWebResponse)req.GetResponse()) { //StreamReader read = new StreamReader(res.GetResponseStream()); string head = res.Headers.ToString(); }

 

PATCH:

 

                var weburi = resourceUrl + "api/data/v9.1/accounts?$filter=accountid eq " + id;
                AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/common", false);
                AuthenticationResult result = authContext.AcquireToken(resourceUrl, clientId, new UserCredential(account, password));
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(weburi);
                req.Method = "PATCH";
                req.Accept = "application/json";
                req.ContentType = "application/json; charset=utf-8";
                req.Headers.Add("OData-MaxVersion", "4.0");
                req.Headers.Add("OData-Version", "4.0");
                
                req.Headers.Set("Authorization", "Bearer " + result.AccessToken);
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

                var newSurveyResult = new JObject
                        {
                            {"stringvalue", "Hello World"},
                            {"intvalue", 123 },
                            { "booleanvalue" , true}
                        };


                byte[] data = Encoding.UTF8.GetBytes(newSurveyResult.ToString());
                Stream newStream = req.GetRequestStream();
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
                {
                    StreamReader read = new StreamReader(res.GetResponseStream());
                }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
asp.netC#光标离开事件发布时间:2022-07-13
下一篇:
c#截取字符串发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap