The problem is that I think the exception block is being triggered (because when I remove the try-catch, I get a server error (500) message. But I don't see the Console.Out lines I put in the catch block. My Console:
The thread 'vshost.NotifyLoad' (0x1a20) has exited with code 0 (0x0). The thread '' (0x1988) has exited with code 0 (0x0). The thread 'vshost.LoadReference' (0x1710) has exited with code 0 (0x0). 'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)): Loaded 'c:\users\l. preston sego iii\documents\visual studio 11\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe', Symbols loaded. 'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. A first chance exception of type 'System.Net.WebException' occurred in System.dll The thread 'vshost.RunParkingWindow' (0x184c) has exited with code 0 (0x0). The thread '' (0x1810) has exited with code 0 (0x0). The program '[2780] ConsoleApplication1.vshost.exe: Program Trace' has exited with code 0 (0x0). The program '[2780] ConsoleApplication1.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).
31.1k 12 12 gold badges 105 105 silver badges 133 133 bronze badges
asked Mar 8, 2012 at 15:35
NullVoxPopuli NullVoxPopuli
64.6k 76 76 gold badges 213 213 silver badges 360 360 bronze badges
Also, have you put break points in there to see where, exactly, it is blowing up?
Commented Mar 8, 2012 at 15:41
this is result from output window but not console
Commented Mar 8, 2012 at 15:41
Commented Mar 8, 2012 at 15:43
The ASP.NET Web API has replaced the WCF Web API previously mentioned.
I thought I'd post an updated answer since most of these responses are from early 2012, and this thread is one of the top results when doing a Google search for "call restful service C#".
Current guidance from Microsoft is to use the Microsoft ASP.NET Web API Client Libraries to consume a RESTful service. This is available as a NuGet package, Microsoft.AspNet.WebApi.Client. You will need to add this NuGet package to your solution.
Here's how your example would look when implemented using the ASP.NET Web API Client Library:
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; namespace ConsoleProgram < public class DataObject < public string Name < get; set; >> public class Class1 < private const string URL = "https://sub.domain.com/objects.json"; private string urlParameters = "?api_key=123"; static void Main(string[] args) < HttpClient client = new HttpClient(); client.BaseAddress = new Uri(URL); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); // List data response. HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs. if (response.IsSuccessStatusCode) < // Parse the response body. var dataObjects = response.Content.ReadAsAsync>().Result; //Make sure to add a reference to System.Net.Http.Formatting.dll foreach (var d in dataObjects) < Console.WriteLine("", d.Name); > > else < Console.WriteLine("()", (int)response.StatusCode, response.ReasonPhrase); > // Make any other calls using HttpClient here. // Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous. client.Dispose(); > > >
If you plan on making multiple requests, you should re-use your HttpClient instance. See this question and its answers for more details on why a using statement was not used on the HttpClient instance in this case: Do HttpClient and HttpClientHandler have to be disposed between requests?
For more details, including other examples, see Call a Web API From a .NET Client (C#)
31.5k 22 22 gold badges 109 109 silver badges 132 132 bronze badges answered Jul 3, 2013 at 22:20 Brian Swift Brian Swift 5,876 2 2 gold badges 15 15 silver badges 9 9 bronze badgesThanks! I needed to install the WebApi client NuGet package for this to work for me: Install-Package Microsoft.AspNet.WebApi.Client
Commented May 22, 2014 at 7:38If you need to mock out your REST integration, even with the client libraries it's still not easy. Try RestSharp?
Commented Jan 7, 2016 at 15:55To make this answer even better than it already is, you should wrap the HttpClient declaration into a using statement to better manage your resource :)
Commented Sep 13, 2016 at 13:07Tried to use but unable to use ReadAsAsync(), getting error "HttpContent does not contain a definition for 'ReadAsAsync' and no extension method.
Commented Mar 27, 2017 at 10:37@RobertGreenMBA: To get the extension method ReadAsAsync() , add a reference to System.Net.Http.Formatting.dll . (Intuitive, right?)
Commented Jun 8, 2017 at 19:34My suggestion would be to use RestSharp. You can make calls to REST services and have them cast into POCO objects with very little boilerplate code to actually have to parse through the response. This will not solve your particular error, but it answers your overall question of how to make calls to REST services. Having to change your code to use it should pay off in the ease of use and robustness moving forward. That is just my two cents though.
namespace RestSharpThingy < using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using RestSharp; public static class Program < public static void Main() < Uri baseUrl = new Uri("https://httpbin.org/"); IRestClient client = new RestClient(baseUrl); IRestRequest request = new RestRequest("get", Method.GET) < Credentials = new NetworkCredential("testUser", "P455w0rd") >; request.AddHeader("Authorization", "Bearer qaPmk9Vw8o7r7UOiX-3b-8Z_6r3w0Iu2pecwJ3x7CngjPp2fN3c61Q_5VU3y0rc-vPpkTKuaOI2eRs3bMyA5ucKKzY1thMFoM0wjnReEYeMGyq3JfZ-OIko1if3NmIj79ZSpNotLL2734ts2jGBjw8-uUgKet7jQAaq-qf5aIDwzUo0bnGosEj_UkFxiJKXPPlF2L4iNJSlBqRYrhw08RK1SzB4tf18Airb80WVy1Kewx2NGq5zCC-SCzvJW-mlOtjIDBAQ5intqaRkwRaSyjJ_MagxJF_CLc4BNUYC3hC2ejQDoTE6HYMWMcg0mbyWghMFpOw3gqyfAGjr6LPJcIly__aJ5__iyt-BTkOnMpDAZLTjzx4qDHMPWeND-TlzKWXjVb5yMv5Q6Jg6UmETWbuxyTdvGTJFzanUg1HWzPr7gSs6GLEv9VDTMiC8a5sNcGyLcHBIJo8mErrZrIssHvbT8ZUPWtyJaujKvdgazqsrad9CO3iRsZWQJ3lpvdQwucCsyjoRVoj_mXYhz3JK3wfOjLff16Gy1NLbj4gmOhBBRb8rJnUXnP7rBHs00FAk59BIpKLIPIyMgYBApDCut8V55AgXtGs4MgFFiJKbuaKxq8cdMYEVBTzDJ-S1IR5d6eiTGusD5aFlUkAs9NV_nFw"); request.AddParameter("clientId", 123); IRestResponse response = client.Execute(request); if (response.IsSuccessful) < response.Data.Write(); >else < Console.WriteLine(response.ErrorMessage); >Console.WriteLine(); string path = Assembly.GetExecutingAssembly().Location; string name = Path.GetFileName(path); request = new RestRequest("post", Method.POST); request.AddFile(name, File.ReadAllBytes(path), name, "application/octet-stream"); response = client.Execute(request); if (response.IsSuccessful) < response.Data.Write(); >else < Console.WriteLine(response.ErrorMessage); >Console.ReadLine(); > private static void Write(this RootObject rootObject) < Console.WriteLine("clientId: " + rootObject.args.clientId); Console.WriteLine("Accept: " + rootObject.headers.Accept); Console.WriteLine("AcceptEncoding: " + rootObject.headers.AcceptEncoding); Console.WriteLine("AcceptLanguage: " + rootObject.headers.AcceptLanguage); Console.WriteLine("Authorization: " + rootObject.headers.Authorization); Console.WriteLine("Connection: " + rootObject.headers.Connection); Console.WriteLine("Dnt: " + rootObject.headers.Dnt); Console.WriteLine("Host: " + rootObject.headers.Host); Console.WriteLine("Origin: " + rootObject.headers.Origin); Console.WriteLine("Referer: " + rootObject.headers.Referer); Console.WriteLine("UserAgent: " + rootObject.headers.UserAgent); Console.WriteLine("origin: " + rootObject.origin); Console.WriteLine("url: " + rootObject.url); Console.WriteLine("data: " + rootObject.data); Console.WriteLine("files: "); foreach (KeyValuePairkvp in rootObject.files ?? Enumerable.Empty()) < Console.WriteLine("\t" + kvp.Key + ": " + kvp.Value); >> > public class Args < public string ClientId < get; set; >> public class Headers < public string Accept < get; set; >public string AcceptEncoding < get; set; >public string AcceptLanguage < get; set; >public string Authorization < get; set; >public string Connection < get; set; >public string Dnt < get; set; >public string Host < get; set; >public string Origin < get; set; >public string Referer < get; set; >public string UserAgent < get; set; >> public class RootObject < public Args args < get; set; >public Headers Headers < get; set; >public string Origin < get; set; >public string Url < get; set; >public string Data < get; set; >public Dictionary Files < get; set; >> >