How do I make calls to a REST API using C#?

后端 未结 15 1608
面向向阳花
面向向阳花 2020-11-22 08:10

This is the code I have so far:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Net.Http;
usi         


        
相关标签:
15条回答
  • 2020-11-22 09:02

    Check out Refit for making calls to REST services from .NET. I've found it very easy to use:

    Refit: The automatic type-safe REST library for .NET Core, Xamarin and .NET

    Refit is a library heavily inspired by Square's Retrofit library, and it turns your REST API into a live interface:

    public interface IGitHubApi {
            [Get("/users/{user}")]
            Task<User> GetUser(string user);
    }
    
    // The RestService class generates an implementation of IGitHubApi
    // that uses HttpClient to make its calls:
    
    var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com");
    
    var octocat = await gitHubApi.GetUser("octocat");
    
    0 讨论(0)
  • 2020-11-22 09:03

    I did it in this simple way, with Web API 2.0. You can remove UseDefaultCredentials. I used it for my own use cases.

    List<YourObject> listObjects = new List<YourObject>();
    
    string response = "";
    using (var client = new WebClient() { UseDefaultCredentials = true })
    {
         response = client.DownloadString(apiUrl);
    }
    
    listObjects = JsonConvert.DeserializeObject<List<YourObject>>(response);
    return listObjects;
    
    0 讨论(0)
  • 2020-11-22 09:07

    The first step is to create the helper class for the HTTP client.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    
    namespace callApi.Helpers
    {
        public class CallApi
        {
            private readonly Uri BaseUrlUri;
            private HttpClient client = new HttpClient();
    
            public CallApi(string baseUrl)
            {
                BaseUrlUri = new Uri(baseUrl);
                client.BaseAddress = BaseUrlUri;
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
            }
    
            public HttpClient getClient()
            {
                return client;
            }
    
            public HttpClient getClientWithBearer(string token)
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                return client;
            }
        }
    }
    

    Then you can use this class in your code.

    This is an example of how you call the REST API without bearer using the above class.

    // GET API/values
    [HttpGet]
    public async Task<ActionResult<string>> postNoBearerAsync(string email, string password,string baseUrl, string action)
    {
        var request = new LoginRequest
        {
            email = email,
            password = password
        };
    
        var callApi = new CallApi(baseUrl);
        var client = callApi.getClient();
        HttpResponseMessage response = await client.PostAsJsonAsync(action, request);
        if (response.IsSuccessStatusCode)
            return Ok(await response.Content.ReadAsAsync<string>());
        else
            return NotFound();
    }
    

    This is an example of how you can call the REST API that require bearer.

    // GET API/values
    [HttpGet]
    public async Task<ActionResult<string>> getUseBearerAsync(string token, string baseUrl, string action)
    {
        var callApi = new CallApi(baseUrl);
        var client = callApi.getClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        HttpResponseMessage response = await client.GetAsync(action);
        if (response.IsSuccessStatusCode)
        {
            return Ok(await response.Content.ReadAsStringAsync());
        }
        else
            return NotFound();
    }
    

    You can also refer to the below repository if you want to see the working example of how it works.

    https://github.com/mokh223/callApi

    0 讨论(0)
提交回复
热议问题