简体   繁体   中英

how to call web api or other restful web services in 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" };
    }
}

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

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

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 !

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM