4

I want to make HTTP calls to various services, POST/GET/DELETE.., and read responses JSON AND XML, How do I do this in C# on servers side?

In short: How to make Api call from Asp.Net Core C#.

Client side Ajax doesn't work, (for cross domains)

6
  • 1
    Just build the same request server side using the HttpClient or use 3rd party build like RestSharp or Flurl Commented Mar 26, 2019 at 14:03
  • 1
    "API call" doesn't mean anything. POST/GET etc are HTTP calls. The built-in option in .NET Core is HttpClient. What do you mean by XML services though? SOAP services or REST with XML? In the first case you need to use WCF to generate a proxy from the service's WSDL file. In the second one just use HttpClient with the correct body Commented Mar 26, 2019 at 14:04
  • 2
    "Client side Ajax dosn't work", could you provide code what you have tried so far? Commented Mar 26, 2019 at 14:35
  • 1
    Maybe some sample code, to get us started on helping. Commented Mar 26, 2019 at 14:42
  • Alexander, you can't make cross domain call via ajax right ?, (I read it somewhere, that you can't because of security reasons.) It works fine to get data, from my own api. Commented Mar 27, 2019 at 5:57

2 Answers 2

7

Try this code: To make Api call from Asp.Net Core, Server Side (C#).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace core.api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        [HttpGet]
        public async  Task<ActionResult<string>> Get()
        {
            string url="https://jsonplaceholder.typicode.com/todos"; // sample url
            using (HttpClient client = new HttpClient())
            {
                return  await client.GetStringAsync(url);
            }
        }
    }

}

Sign up to request clarification or add additional context in comments.

Comments

7

Use ajax to call controler:

$.ajax({                                        
        type: "GET",      
        url: "/API/Gumtreetoken?user=username&pasword=password",                                       
        success: function (atsakas) {                                       
              alert(atsakas);
        },
        error: function (error) {
              alert("error");         
        }
});

And, from controller I use HTTPClient to make POST call and get needed values from XML responce.

    [Authorize]
    [Route("API/Gumtreetoken")]
    public IActionResult GumtreePost(string user, string pasword)
    {
        string atsakas = "";
        string token = "";
        string id = "";

        using (HttpClient client = new HttpClient())
        {
            //parametrai (PARAMS of your call)
            var parameters = new Dictionary<string, string> { { "username", "YOURUSERNAME" }, { "password", "YOURPASSWORD" } };
            //Uzkoduojama URL'ui 
            var encodedContent = new FormUrlEncodedContent(parameters);               
            try
            {
                //Post http callas.
                HttpResponseMessage response =  client.PostAsync("https://feed-api.gumtree.com/api/users/login", encodedContent).Result;
                //nesekmes atveju error..
                response.EnsureSuccessStatusCode();
                //responsas to string
                string responseBody = response.Content.ReadAsStringAsync().Result;
                
                atsakas = responseBody;
               
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
            //xml perskaitymui
            XmlDocument doc = new XmlDocument();
            //xml uzpildomas api atsakymu
            doc.LoadXml(@atsakas);
            //iesko TOKEN
            XmlNodeList xmltoken = doc.GetElementsByTagName("user:token");
            //iesko ID
            XmlNodeList xmlid = doc.GetElementsByTagName("user:id");

            token = xmltoken[0].InnerText;
            id = xmlid[0].InnerText;

            atsakas = "ID: " + id + "   Token: " + token;
            
        }
        return Json(atsakas);
    }

This should be Async, so, you could do like this:

    [Authorize]
    [Route("API/Gumtreetoken")]
    public async Task<IActionResult> GumtreePost(string user, string pasword)
    {
        string atsakas = "";
        string token = "";
        string id = "";
        using (HttpClient client = new HttpClient())
        {
            var parameters = new Dictionary<string, string> { { "username", "YOURUSERNAME" }, { "password", "YOURPASSWORD" } };
            var encodedContent = new FormUrlEncodedContent(parameters);               
            try
            {
                HttpResponseMessage response = await client.PostAsync("https://feed-api.gumtree.com/api/users/login", encodedContent);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();                    
                atsakas = responseBody;                   
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(@atsakas);
            XmlNodeList xmltoken = doc.GetElementsByTagName("user:token");
            XmlNodeList xmlid = doc.GetElementsByTagName("user:id");
            token = xmltoken[0].InnerText;
            id = xmlid[0].InnerText;
            atsakas = "ID: " + id + "   Token: " + token;
        }
        return Json(atsakas);
    }

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.