Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

asp.net - 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# ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...