Home > Back-end >  Calling a Rest-API using C#
Calling a Rest-API using C#

Time:02-11

I'm trying to call a rest-api in asp.net to test if people are trustworthy with paying by invoice. The problem is that i've never used any rest-api before and couldn't find a good example on how to call it in asp.net. Can someone help me?

Here are the values that the request needs.

enter image description here

/api/v1/RiskCube/claim

{
  "shopId": "20071992",
  "orderProcessId": "ref001",
  "ipAddress": null,
  "macAddress": null,
  "customerId": "cus001",
  "billingAddress": {
    "type": "Consumer",
    "businessName": null,
    "firstName": "Martin",
    "lastName": "Früh",
    "co": null,
    "street": "Funkenbüelstrasse",
    "houseNumber": "1",
    "postCode": "9243",
    "locationName": "Jonschwil",
    "country": "CH",
    "email": null,
    "phone": null,
    "dateOfBirth": null
  },
  "shippingAddress": null,
  "orderAmount": 1200
}

CodePudding user response:

So, you can try out using HttpClient to call another API. Ex. https://docs.microsoft.com/ru-ru/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0 . And you can use libraries for that like Refit https://github.com/reactiveui/refit

edit: Link in english https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0

CodePudding user response:

Thanks for all the answers in the end i came out with that result.

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://service-zs.riskcube.ch/api/v1/RiskCube/claim");
        request.ContentType = "application/json";
        request.Method = "POST";
        request.Headers.Add("Authorization", "X-API-KEY"); //Add a valid API Key
        if (creditReformModel != null)
        {
            string postData = JsonConvert.SerializeObject(creditReformModel);
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(postData);
            }
        }
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

I think for most people @Serhii answer is better than what i came up with.

  • Related