how to call web api or other restful web services in c#

让人想犯罪 __ 提交于 2019-12-13 09:45:51

问题


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" };
    }
}

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# ?


回答1:


To call WEB API in c# you can use the HttpClient class.

public class Client
{
   private readonly string baseUri;
   private static HttpClient _client;

    public Client(string baseUri)
    {
        this.baseUri = baseUri;

        _client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true })
        {
            BaseAddress = new Uri(baseUri)
        };

        _client.DefaultRequestHeaders.Accept.Clear();
        _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<SomeResource> GetResourceById(int Id)
    {
        var path = $"{baseUri}/Resources/{Id}";

        var response = await _client.GetAsync(path);

        return await response.Content.ReadAsAsync<SomeResource>();           
    }



回答2:


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;
        }
    }

so easier !




回答3:


Create an HttpClient (https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx) and call its GetAsync() https://msdn.microsoft.com/en-us/library/hh158912(v=vs.118).aspx method. I'm assuming you have this running locally so your Uri is probably something like http://localhost/test/get depending on how you have Visual Studio configured when you press F5. Here's a complete example: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client



来源:https://stackoverflow.com/questions/46913786/how-to-call-web-api-or-other-restful-web-services-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!