Net Core教程

c# HttpClient 给webapi post传递并传参

本文主要是介绍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;
                }
}

 

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;

 

这篇关于c# HttpClient 给webapi post传递并传参的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!