如何在C#中调用Web API或其他宁静的Web服务 [英] how to call web api or other restful web services in c#
问题描述
我可以通过ajax请求调用每个 webApi
方法,但是用c#无法做到.这是一个简单的Web api,每个人都可以在asp.net mvc Web api中创建它,但是我找不到任何有关调用的示例,并且无法通过c#进行编程获取.
I can call every webApi
methods by ajax request but I can't do it by c#.
this is a simple web api which every body can create it in asp.net mvc web api but I can't find any example about call and get it programmatically by c#.
public class TestController : ApiController
{
// GET: api/Test
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
请有人告诉我如何在C#中调用此Web api方法并获取这2个值.我们如何在c#中从Web服务( RestFull
-无参考)中获取价值?
please some body say me how can I call this web api method in c# and get these 2 values. how can we get value from a web service(RestFull
-without reference) in c# ?
推荐答案
答案是这样的……所有给出负面反应的人都可以这样做,而不是负面反应:
the answer is this...all persons who give negative reaction can do this instead of negative reactions:
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
那么容易!
这篇关于如何在C#中调用Web API或其他宁静的Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!