Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...