1

I am struggling with Rest call. Here is my code and it is working 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 + "");
        client.DefaultRequestHeaders.Accept.Clear();
       **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();
            }
        }
    }
}

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.)

Eduard Malakhov
  • 1,095
  • 4
  • 13
  • 25
RMD
  • 311
  • 1
  • 7
  • 22
  • 5
    Kind of unrelated, but I can really recomment using restSharp (http://restsharp.org/) for such things - it's a very powerful library – Mafii Mar 29 '18 at 07:00
  • @Mafii It is absolutely related. Don't reinvent the wheel. – Fildor Mar 29 '18 at 07:10

1 Answers1

0

There are a couple of things about your code I do not understand.

  1. What is HomeController.contentType all about? The name "HomeController" suggests you're writing an ASP.NET MVC Controller (serverside). Though you seem to be writing something intended to be used as a HTTP client. But I could be mistaken or mislead here.
  2. You are reading a Json response, then loading it as a Xml document?

I'll try to answer anyway.

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

The Accept header sent by the client (you) tells the server that you accept the given content type. If you send Accept application/xml you tell the server you prefer if the response is Xml.

Your code seem to assume the response's content type is always Json.

You could include both application/xml and application/json as Accept headers in your request. The server should honor that request and pick the first supported content type for it's response.

When processing the response you should check the actual content type and handle the response content appropriately.

Remember that Accept only tells the server that you prefer those content types. The server may decide not to honor your whishes and can return any content type it desires.

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

If you mean tokenized as in a query parameter you should probably handle your query parameters as a collection rather than a hardcoded formatted string. Check out the NameValueCollection class and this SO question on NameValueCollection to query string.

To handle cookies, you basically need to copy/re-use the cookie collection returned in a response in the next request. See this SO question on how to inject cookies when you create a new HttpClient.

... but it's much easier to use a library

As you already discovered, making a robust REST/HTTP client is not a easy task. And as @Mafii and @Fildor already pointed out in comments there are already numerous libraries available. RestSharp (https://restsharp.org) being one very popular.

Adam B
  • 506
  • 1
  • 5
  • 13