RESTful Web API Notes
When using RESTful Web API, it is important to note that the old WCF Web API has been replaced by ASP.NET Web API. In order to use RESTful services, Microsoft recommends using the Microsoft ASP.NET Web API client library.
Creating REST API calls in C#
The following is an updated example using the ASP.NET Web API client library:
<code class="language-csharp">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) { using (HttpClient client = new HttpClient()) // 使用using语句确保HttpClient被正确释放 { client.BaseAddress = new Uri(URL); // 添加JSON格式的Accept头。 client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); try { // 使用异步方法避免阻塞调用 var response = client.GetAsync(urlParameters).Result; if (response.IsSuccessStatusCode) { // 解析响应体。 var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result; foreach (var d in dataObjects) { Console.WriteLine("{0}", d.Name); } } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } } catch (HttpRequestException e) { Console.WriteLine($"HTTP请求异常:{e.Message}"); } catch (Exception e) { Console.WriteLine($"发生异常:{e.Message}"); } } } } }</code>
Exception handling
In the code you provided earlier, you may have noticed that the exception handling block does not work. This is because the WebException is not thrown. When using the ASP.NET Web API client library, exceptions are thrown as HttpRequestException.
To handle exceptions using the new library, you can use a try-catch block like this:
<code class="language-csharp">try { // 在此处进行请求 } catch (HttpRequestException e) { // 在此处处理异常 } catch (Exception e) // 捕获更通用的异常 { // 处理其他类型的异常 }</code>
Improvements: Used the using
statement to ensure that HttpClient
is released correctly to avoid resource leaks; replaced blocked GetAsync
calls with asynchronous methods to improve program efficiency; added more comprehensive exception handling, including Exception
Base class to catch more types of exceptions and provide clearer exception information output. The code also corrects the spelling error of ienumerable
.
The above is the detailed content of How Can I Use C# to Consume REST APIs and Handle Potential Exceptions?. For more information, please follow other related articles on the PHP Chinese website!