2

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 "";
        }
    }
}
1
  • Web API is an ASP.NET Application. WebRequest is obsolete, replaced by HttpClient since 2012. In fact, in .NET Core HttpWebRequest calls HttpClient underneat Commented Jun 17, 2022 at 15:12

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I'm not quite sure with regards to your reference for a path-to-api? as for the rest, it's returning errors to the following: "Cannot implicitly convert type '<system.threading.tasks.tasks <system.net.http.httpresponsemessage>' to 'system.net.http.httpresponsemessage' The best overloaded method match for 'system.xml.linq.xdocument.parse(string) has some invalid arguments argument 1: cannot convert from 'system.threading.tasks.task<string> to 'string' Not sure if I'm missing something here?
I've updated the code. You need to use it within an async method. Looks like you were using it in a plain old sync method. Regarding the path to api, it should have an endpoint like www.apiurl.com/getthings. "/getthings" would be your path. If not, just use a "/".
So I should probably mention that this is one part of a larger program where by it's a property feed integration. I've implemented your code, however when using the below in another part of the app: private static void UpdateWebLetMCApiProperties() { WebApi_LetMCGetBranches branch = new WebApi_LetMCGetBranches(); String webApi_LetMCbranch = branch.GetLetMCBranch(); I get the following error: Cannot implicitly convert type 'System.Threading.Tasks.Task<string>' to 'string'. Any further advice? I really appreciate all the help.
Again, you're not implementing it as an async method, so it won't work properly. You'll see my code returns an async Task<string>, not a string. You'll need to call this asynchronously like await GetLetMCBranch() within a task.run or async method. Please see learn.microsoft.com/en-us/dotnet/csharp/programming-guide/… for more information regarding async methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.