Consume Rest API in C #

4

I would like you to guide me a bit with this. I am trying to consume an API Rest in C # and have an authentication where I must pass these parameters or values: username , password , client_id , client_secret , grant_type , scope but I do not know how to pass those values.

I'm doing something like this:

HttpWebRequest request = WebRequest.Create("MiDireccionAPI") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded"; //"application/json; charset=utf-8";
request.Headers.Add("username", "miUsuario");
request.Headers.Add("password", "MiClave");
request.Headers.Add("grant_type", "Migrant_type");
request.Headers.Add("client_id", "Miclient_id");

HttpWebResponse response = request.GetResponse() as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
string resp = reader.ReadToEnd();

And it's supposed that he should return a token like this and a code 200 :

eyJhbGciOiJSUzI1NiJ9.eyJqdGkiOiI0ZTJjZTBlZC02ZDQwLTRmY2EtODgwNS1lMzg0NzdmZmVlNWUiLCJleHAiOjE0OTEyMzEyMzUsIm5iZiI6MCwiaWF0IjoxNDkxMjMwOTM1LCJpc3MiOiJodHRwczovL2lkcC5jb21wcm9iYW50ZXNlbGVjdHJvbmljb3MuZ28uY3IvYXV0aC9yZWFsbXMvcnV0LXN0YWciLCJhdWQiOiJhcGktc3RhZyIsInN1YiI6ImQ1NzQ2NDc0LWVhZWYtNDNkNS05MmE2LTQ4MWQyM2ZlOTM5OSIsInR5cCI6IkJlYXJlciIsImF6cCI6ImFwaS1zdGFnIiwic2Vzc2lvbl9zdGF0ZSI6IjM0Y2Y2MWJiLWU4ZTgtNDYzZS1iMTJjLTFjNTFhYzdmMGE3ZCIsImNsaWVudF9zZXNzaW9uIjoiZDQzNjRmOGUtZmFjOS00NjRiLWE2NzgtYWI2OWU5ODE0YzU4IiwiYWxsb3dlZC1vcmlnaW5zIjpbXSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJ2aWV3LXByb2ZpbGUiXX19LCJuYW1lIjoiR0VTVElPTiBFTiBURUNOT0xPR0lBIEUgSU5GT1JNQUNJT04gRyBUIEkgU09DSUVEQUQgQU5PTklNQSAiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJjcGotMy0xMDEtMjI1ODkwQHN0YWcuY29tcHJvYmFudGVzZWxlY3Ryb25pY29zLmdvLmNyIiwiZ2l2ZW5fbmFtZSI6IkdFU1RJT04gRU4gVEVDTk9MT0dJQSBFIElORk9STUFDSU9OIEcgVCBJIFNPQ0lFREFEIEFOT05JTUEiLCJwb2xpY3ktaWQiOiI1OGE2MjAzMzc2ZWFlMTQwOGNlNWU3ZGQiLCJlbWFpbCI6ImNwai0zLTEwMS0yMjU4OTBAc3RhZy5jb21wcm9iYW50ZXNlbGVjdHJvbmljb3MuZ28uY3IifQ.UyHf8uJg3y6i0mKBlAsCpDKCfO_s5rASurzGgcBfc0Y8jm0cPPPZLNqKbQYXm0NUvpUVnNuC5O634cUFoOFlAOaAQwdnQbki34nXcRn9vb3YXj7bpOKmK1RFoB-Hf6rJ843VQQzC4vHxMUTOOa5k32gFNcWEnlVHclitGRZezJbozYeqCUi3VbzShMPKFAAT5gcDZgw6tgl7gbwiu4Mf4vCvJamKTfaziBBhj-3gVe5yXnEp-WfaH87B3rV9xM69SJ-EGJ1wxfUN3E7PTqjanYGDjA24UY-NRASwfJV9Gwyikk4irSGNCbAiRm70NCaGwFEMjzBetwp0avG0g_tu9Q

But I get error 400 because I imagine that the past of the parameters is wrong.

If someone clarifies to me how to pass this type of values to an API, since I am a beginner in this and I did not find something that really serves me.

EDIT:

I have a website made in asp.net that makes invoices and I must consume this API and which uses OAuth 2.0, this API is from a government entity in my country that is responsible for receiving invoices for this API but this API a token must be generated to be able to send what is occupied.

What I'm trying to do is generate that token to send the invoices.

This website is published on a server.

    
asked by Alex 03.04.2017 в 17:23
source

2 answers

2

Explore the api you want to connect to using a tool like Postman , with it you can similar the Request in different ways until you discover what are the exact parameters you need, what kind of request (GET, POST, ETC) and where to place them (header, body, etc).

Already with that information it is easy to create a client.

Seeing your example, modify it in the following way:

HttpWebRequest request = WebRequest.Create("MiDireccionAPI") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded"; 

// Metodo modificado
string postData = "username=miUsuraio&password=MiClave&grant_type=password&client_id=Miclient_id";    byte[] byteArray = Encoding.UTF8.GetBytes (postData);  
request.ContentLength = byteArray.Length;  
using (Stream dataStream = request.GetRequestStream (){
    using (StreamWriter stmw = new StreamWriter(dataStream))
    {
        stmw.Write(postData);
    }
    dataStream.Write (byteArray, 0, byteArray.Length);  
}

HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    string resp = reader.ReadToEnd();
}

The grant_type was modified, when you are authenticating, the grant_type = password is sent to request the token.

Another point to consider is that if the server you are connecting to was made with Web API 2 try to find a url of the type:

link

Since authentication by default is set to / Token

EDIT:

Change the example to use POST instead of Headers.

    
answered by 03.04.2017 в 18:37
2

You can try to implement it in this way, which is what I always use and it works for me.

first you will need the Newtonsoft.Json to de-serialize the answer and so in case you get errors you can know what the error was. You install it from the NuGet package manager

Now to implement the call to the api you will also need to add references to

System.Net.Http    
System.Net.Http.formatting

and with this you can already use this code, substituting the values that you need to send in the headers and the object that has to be sent.

try
    {
        //declare api client 
        static HttpClient client = new HttpClient();
        //Initialize api client
        if (client.BaseAddress == null)
            client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings.Get("WS_URL"));
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        //Add headers
        client.DefaultRequestHeaders.Add("X_PUBLIC_KEY", PublicKey.ToString());
        client.DefaultRequestHeaders.Add("X_TIME", date);
        client.DefaultRequestHeaders.Add("X_TOKEN", CreateToken(PrivateKey + date, PrivateKey));

        //Call client.PostAsJsonAsync to send a POST request to the appropriate URI   
        HttpResponseMessage resp = client.PostAsJsonAsync("api/Vehiculo/Add", object).Result;
        //This method throws an exception if the HTTP response status is an error code.  
        //var xx = resp.EnsureSuccessStatusCode();
        if (resp.IsSuccessStatusCode)
        {
            var resultado = resp.Content.ReadAsAsync<Vehiculo>().Result;
            return resultado;
        }
        else
        {
            var resultado = resp.Content.ReadAsStringAsync().Result;
            var result = JsonConvert.DeserializeObject<ResultServer>(resultado);
            throw new Exception(string.Format("Message:{0}, ExceptionMessage: {1}", result.Message, result.ExceptionMessage));
        }
    }
    catch (Exception ex)
    {
        throw new Exception(string.Format("AddVehicle - Error: {0}", ex.Message));
    }

I hope this code will help you, and I'll keep everything up to date.

Update ...

From what I see in the image of your postman, the data you send in the call is not a header, but an object with the parameters username, password, etc ...

then the problem is that in your code you are adding those values as headers. What you have to do is create a class that contains those parameters with the same name as you are sending them, and instantiate it by assigning values, to send it in your call to the api, which in the example code that you attach before is done in this line:

//Call client.PostAsJsonAsync to send a POST request to the appropriate URI   
        HttpResponseMessage resp = client.PostAsJsonAsync("api/Vehiculo/Add", object).Result;

Being object, the instance to your created class.

I hope I have been of help, I stay tuned

    
answered by 07.04.2017 в 22:54