温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在C#项目中调用WebApi

发布时间:2021-04-19 16:28:59 来源:亿速云 阅读:263 作者:Leah 栏目:开发技术

如何在C#项目中调用WebApi?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

1.WebRequest方式

Post:

private void button1_Click(object sender, EventArgs e)
        {
           string ss= HttpPost("http://localhost:41558/api/Demo/PostXXX", "{Code:\"test089\",Name:\"test1\"}");
        }

        public static string HttpPost(string url, string body)
        {
            //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";
       
            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

Get:

private void button1_Click(object sender, EventArgs e)
        {
            string ss = HttpGet("http://localhost:41558/api/Demo/GetXXX?Name=北京");
        }

        public static string HttpGet(string url)
        {
            //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";
           
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

2.HttpClient 方式

Post:

private async void button2_Click(object sender, EventArgs e)
{
     HttpClient client = new HttpClient();
     //由HttpClient发出Delete Method
     HttpResponseMessage response = await client.DeleteAsync("http://localhost:41558/api/Demo"+"/1");
     if (response.IsSuccessStatusCode)
         MessageBox.Show("成功");
}

private async void button3_Click(object sender, EventArgs e)
{
     //创建一个处理序列化的DataContractJsonSerializer
     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People));
     MemoryStream ms = new MemoryStream();
     //将资料写入MemoryStream
     serializer.WriteObject(ms, new People() { Id = 1, Name = "Hello ni" });
     //一定要在这设定Position
     ms.Position = 0;
     HttpContent content = new StreamContent(ms);//将MemoryStream转成HttpContent
     content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
     HttpClient client = new HttpClient();
     //由HttpClient发出Put Method
     HttpResponseMessage response = await client.PutAsync("http://localhost:41558/api/Demo"+ "/1", content);
     if (response.IsSuccessStatusCode)
         MessageBox.Show("成功");
}

Get:

using (WebClient client = new WebClient())
{
     client.Headers["Type"] = "GET";
     client.Headers["Accept"] = "application/json";
     client.Encoding = Encoding.UTF8;
     client.DownloadStringCompleted += (senderobj, es) =>
     {
         var obj = es.Result;
     };
     client.DownloadStringAsync("http://localhost:41558/api/Demo");
}

关于如何在C#项目中调用WebApi问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI