在后端C#中 call web api

我们要想使用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());
                }

原文地址:https://www.cnblogs.com/TheMiao/p/12289293.html

时间: 2024-11-06 07:31:58

在后端C#中 call web api的相关文章

对一个前端AngularJS,后端OData,ASP.NET Web API案例的理解

依然chsakell,他写了一篇前端AngularJS,后端OData,ASP.NET Web API的Demo,关于OData在ASP.NET Web API中的正删改查没有什么特别之处,但在前端调用API时,把各种调用使用$resouce封装在一个服务中的写法颇有借鉴意义. 文章:http://chsakell.com/2015/04/04/asp-net-web-api-feat-odata/源码:https://github.com/chsakell/odatawebapi 首先是领域模

购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(3)--Idetity,OWIN前后端验证

原文:购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(3)--Idetity,OWIN前后端验证 chsakell分享了前端使用AngularJS,后端使用ASP.NET Web API的购物车案例,非常精彩,这里这里记录下对此项目的理解. 文章:http://chsakell.com/2015/01/31/angularjs-feat-web-api/http://chsakell.com/2015/03/07/angularjs-feat-web-api-

购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(2)--前端,以及前后端Session

原文:购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(2)--前端,以及前后端Session chsakell分享了前端使用AngularJS,后端使用ASP.NET Web API的购物车案例,非常精彩,这里这里记录下对此项目的理解. 文章:http://chsakell.com/2015/01/31/angularjs-feat-web-api/http://chsakell.com/2015/03/07/angularjs-feat-web-api-en

购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(1)--后端

原文:购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(1)--后端 chsakell分享了前端使用AngularJS,后端使用ASP.NET Web API的购物车案例,非常精彩,这里这里记录下对此项目的理解. 文章:http://chsakell.com/2015/01/31/angularjs-feat-web-api/http://chsakell.com/2015/03/07/angularjs-feat-web-api-enable-session-

对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(4)

chsakell分享了一个前端使用AngularJS,后端使用ASP.NET Web API的项目. 源码: https://github.com/chsakell/spa-webapi-angularjs文章:http://chsakell.com/2015/08/23/building-single-page-applications-using-web-api-and-angularjs-free-e-book/ 这里记录下对此项目的理解.分为如下几篇: ● 对一个前端使用AngularJ

对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(3)

chsakell分享了一个前端使用AngularJS,后端使用ASP.NET Web API的项目. 源码: https://github.com/chsakell/spa-webapi-angularjs文章:http://chsakell.com/2015/08/23/building-single-page-applications-using-web-api-and-angularjs-free-e-book/ 这里记录下对此项目的理解.分为如下几篇: ● 对一个前端使用AngularJ

对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(1)

chsakell分享了一个前端使用AngularJS,后端使用ASP.NET Web API的项目. 源码: https://github.com/chsakell/spa-webapi-angularjs文章:http://chsakell.com/2015/08/23/building-single-page-applications-using-web-api-and-angularjs-free-e-book/ 这里记录下对此项目的理解.分为如下几篇: ● 对一个前端使用AngularJ

对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(2)

chsakell分享了一个前端使用AngularJS,后端使用ASP.NET Web API的项目. 源码: https://github.com/chsakell/spa-webapi-angularjs文章:http://chsakell.com/2015/08/23/building-single-page-applications-using-web-api-and-angularjs-free-e-book/ 这里记录下对此项目的理解.分为如下几篇: ● 对一个前端使用AngularJ

ASP.NET MVC4中调用WEB API的四个方法

http://tech.it168.com/a2012/0606/1357/000001357231_all.shtml [IT168技术]当今的软件开发中,设计软件的服务并将其通过网络对外发布,让各种客户端去使用服务已经是十分普遍的做法.就.NET而言,目前提供了Remoting,WebService和WCF服务,这都能开发出功能十分强大的服务.然而,越来越多的互联网应用,希望将服务只是通过HTTP发布出去,而不是使用复杂的SOAP协议.为了解决这个问题,ASP.NET WebAPI就出现了.