Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
The following code works for basic authentication.

public async Task RunAsync(string name, string value)
using (var handler = new HttpClientHandler { UseDefaultCredentials = true })
using (var client = new HttpClient(handler))
var byteArray = Encoding.ASCII.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var urlRestGet = HomeController.url;
client.BaseAddress = new Uri(urlRestGet + "?name=" + name + "&value=" + value + "");
**1. if(HomeController.contentType.ToLower()=="xml"){
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

else if (HomeController.contentType.ToLower() == "json")
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = await client.GetAsync(urlRestGet + "?name=" + name + "&value=" + value + "");

if (response.IsSuccessStatusCode)
//Get the response
loginJsonString = await response.Content.ReadAsStringAsync();

//Converting to xml
using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(loginJsonString)))
var output = new XmlDictionaryReaderQuotas();
xmlResult = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(stream, output)).ToString();

What I have tried:

1) If the content type is application/xml am I correct to use line 1 part in the code.

2) How can I make this code more generic. (when the authentication type is different eg: tokenized or cookiebased how can I change this.)

1 solution

I do not have so much experience with rest API but i have done one project for windows phone and Call a Web API From a .NET Client (C#) | Microsoft Docs[^] hellped me very mouch!
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900