Donovan
Donovan

Reputation: 57

Cannot connect ASP.Net application to Web API

I'm currently struggling to get my webAPI to connect with my application. It seems to me that it connects using an "api_key". I have a link to the swagger build to show the web_api seems to be working correctly, but I'm not sure what my application is doing wrong.. Any assistance would be appreciated.

Oh, the error seems to happen after the line LetMCresponse = (HtpWebResponse)LetMCmyrequestt.GetResponse();

Error received: "The underlying connection was closed. An unexpected error occures on a send."

I'm still relatively inexperienced in using ASP.Net as well as WebAPI's. Any assistance would be appreciated

class WebApi_LetMCGetBranches
   {
       public string GetLetMCBranch()
      {

        string url = "https://apiurl.com";


        HttpWebResponse LetMCresponse = null;

        try
        {
            HttpWebRequest LetMCmyrequest = (HttpWebRequest)WebRequest.Create(url);
            

            CredentialCache LetMCmycache = new CredentialCache();
        
            LetMCmyrequest.Credentials = LetMCmycache;
            LetMCmyrequest.Method = HttpMethod.Get;
            LetMCmyrequest.Headers.Add("api_key", "123456");
            LetMCresponse = (HttpWebResponse)LetMCmyrequest.GetResponse();
            Stream s = LetMCresponse.GetResponseStream();
            StreamReader LetMCresponseReader = new StreamReader(s);

            // Now use XmlDocument and XmlReader to get the xml reponse.

            // e.g. Create the reader from the stream and call xmldoc.Load(xmlreader);

            // XmlDocument xmldoc = new XmlDocument();
            XmlReader LetMCreader = XmlReader.Create(LetMCresponseReader);
            LetMCreader.MoveToContent();
            var LetMCxmlDox = XDocument.ReadFrom(LetMCreader);
            var LetMCxmlDoxDes = XDocument.Parse(LetMCxmlDox.ToString());
            //Console.WriteLine(xmlDox.ToString());
            System.Diagnostics.Debug.WriteLine(LetMCxmlDox.ToString());
            foreach (XElement element in LetMCxmlDoxDes.Descendants("branch"))
            {
                if (null != element.Element("name") && element.Element("name").Value == "Peterborough")
                {
                    return element.Element("url").Value;
                }
            }


        }

        catch (WebException ex)
        {

            if (!ex.Message.Contains("The remote server returned an error: (401) Unauthorized."))
            {

                throw;
            }
            else
            {

            }
        }



        return "";
        }
    }
}

Upvotes: 2

Views: 655

Answers (1)

Matthew M.
Matthew M.

Reputation: 1107

You're going to want to use HttpClient instead of WebRequest, as WebRequest is obsolete. Here's some sample code that should help you on your way:

public async Task<string> GetLetMCBranch()
{
    try
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://apiurl.com");
            client.DefaultRequestHeaders.Add("api_key", "123456");

            HttpResponseMessage response = await client.GetAsync("/path-to-api");

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                var LetMCxmlDox = XDocument.Parse(result);
            }
            else
            {
                Console.WriteLine("Internal server Error");
            }
        }
    }
    catch (Exception exc)
    {
        Console.WriteLine(exc);
    }
}

Upvotes: 1

Related Questions