Consuming Web Service with authentication - C#

Asked

Viewed 804 times

0

Good afternoon Personal.

I’m implementing a function in my system to consume data from a web service that requires authentication (Basic Authentication), but I can’t get any feedback. The question is whether the authentication is correct. I searched here on the same site methods to do this and found the following: insert link description here insert link description here

Following these two links I created my method which was as follows:

try
                {
                    var authData = string.Format("{0}:{1}", "Usuario", "Senha");

                    var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));

                    HttpClient cliente = new HttpClient();

                    var uri = new Uri("https://linkdoService");

                    cliente.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);

                    var json = JsonConvert.SerializeObject(usuario, Formatting.Indented);

                    var content = new StringContent(json, Encoding.UTF8);

                    var resposta = await cliente.PostAsync(uri, content);
                }

The code is not complete, because I stop the execution of the application to check what is returning me and in case the variable reply is always "null". Could someone tell me if this method is correct or am forgetting something to accomplish this request.

Obs1: I am using the Postman program for testing, when using the URL and the authentication keys Postman makes the normal return, that is, send a Json and return a Json as well.

Note: I also tested the Json I am sending to the Web Service, in case the Json created by this line:

var json = JsonConvert.SerializeObject(usuario, Formatting.Indented);

works normally on Postman.

Thanks in advance to anyone who can help, give a hint.

  • This is a request for a Webservice or an HTTP Rest?

  • Hello Pedro, is a Web Service same.

  • Where is the usuario in this scope? You compared the generated json to content with your Postman? as well as the Contenttype?

  • Hello Leandro, the "user" is not in this scope because it is a very large declaration and as I tested the Json generated by it (in the json variable) in Postman I believe that the same is not the problem. Regarding the Json generated in "content" I could not compare, when stopping the code at runtime the only information I get is that it is a variable of type {System.Net.Http.Stringcontent}.

  • Include the sending template you are doing on in Postman, it can be a print obfuscating the even sensitive data.

  • Hi Leandro, sorry, I did not understand very well what it is to do. I need to put the model of my user class in Postman? Thank you.

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.