API REST by HttpClient

if you use entities, create the entity for the filters

public class Entity
{
public string company { get; set; }
}

In the main class you can declare the variable URI
const string _serviceUrl = “https://{server}/{application}/api/v1”;

We create a method, for my case I will use a method of CompanyTableset type

CompanyTableset Company()
{
CompanyTableset ds = new CompanyTableset();
try
{
HttpClient client = new HttpClient(); client.BaseAddress = new Uri(_serviceUrl + @“/Erp.BO.CompanySvc/”);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Basic”,
Convert.ToBase64String(
ASCIIEncoding.ASCII.GetBytes(string.Format(“{0}:{1}”, “user”, “pass”)))
);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));

            var data = new Entidades.Entity();
            data.company = "CompanyID";
            var response = client.PostAsJsonAsync("GetByID", data).Result;


            if (response.IsSuccessStatusCode)
            {
                string result = response.Content.ReadAsStringAsync()
                                .ConfigureAwait(false)
                                .GetAwaiter()
                                .GetResult();
                JObject jo = JObject.Parse(result);

                return jo.SelectToken("returnObj", false).ToObject<CompanyTableset>();
            }
        }
        catch (Exception ex)
        {
            ds = null;
            MessageBox.Show(ex.Message);
        }
        return ds;
    }

We call the method and assign it to a grid

/This line bypass certificate SSL/
//ServicePointManager.ServerCertificateValidationCallback += (senderC, cert, chain, sslPolicyErrors) => true;
dataGridView1.DataSource = Company().Company;

I hope that those who have problems with API consumption can solve their difficulties with this option

1 Like