code学习

c# HttpClient 给webapi post传递并传参

public  IHttpActionResult SinkingCommunityData([FromBody]CommunityModel Entitys)
{
           //自己的业务逻辑代码
           //并调用其他接口
          string url = "http://localhost:54150/api/_data"; //创建HttpClient
                using (var http = new HttpClient(handler))
                {
                    
                    http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    StringContent strcontent = new StringContent(JsonConvert.SerializeObject(Entitys), Encoding.UTF8, "application/json");
                    //异步等待回应 
                    HttpResponseMessage response = http.PostAsync(url, strcontent).Result;
                    //确保HTTP成功状态值
                    response.EnsureSuccessStatusCode();
                    string str = response.Content.ReadAsStringAsync().Result;
                }
}      
传递参数的同时传递一个cookie
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
StringContent strcontent = new StringContent(JsonConvert.SerializeObject("aa"), Encoding.UTF8, "application/json");
var message = new HttpRequestMessage(HttpMethod.Post, "your address");
//设置cookie信息
message.Headers.Add("Cookie", "token=" + token);
//设置contetn
message.Content = strcontent;
//发送请求
var httpResponseHeaders = httpClient.SendAsync(message).Result;