Best Practices for REST API Calls in C#
Introduction
This article discusses how to call REST API in C#, solves the problem of exception blocks not being executed, and provides an improved solution using the current ASP.NET Web API client library.
Original code and problems
The original code uses the HttpWebRequest
class to make a POST request to the REST API. However, the exception block appears to be bypassed, causing the error message to not be displayed.
Improved solution using ASP.NET Web API client library
Microsoft currently recommends using the ASP.NET Web API client library to use RESTful services. Here are the improvements to the given code:
<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语句自动释放资源 { 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($"HTTP请求失败: 状态码 {(int)response.StatusCode} - {response.ReasonPhrase}"); // 更高级的错误处理,例如记录日志或抛出自定义异常 } } catch (HttpRequestException ex) { Console.WriteLine($"HTTP请求异常: {ex.Message}"); // 更高级的错误处理,例如记录日志或显示用户友好的错误信息 } catch (Exception ex) { Console.WriteLine($"发生未知异常: {ex.Message}"); // 记录日志或显示用户友好的错误信息 } } } } }</code>
This improvement uses the HttpClient
class to simplify the process of using HTTP-based services and handling responses. It includes explicit exception handling and uses the using
statement to ensure that the HttpClient
instance is released correctly. The use of asynchronous methods also avoids program blocking. Clearer error message output has been added to the code, and more advanced error handling is recommended.
Note:
HttpClient
instance for multiple requests. HttpClient
class follows the "dispose pattern". Best practice is to use a using
statement or manually release the client after all requests have completed. The using
statement has been used in this example. GetAsync
) can improve program performance and avoid blocking the main thread. The Result
attribute blocks until the asynchronous operation completes, but combined with a try-catch
block allows for more efficient exception handling. This revised answer provides a more robust and efficient solution, addressing potential exceptions and improving code clarity. The use of using
and explicit error handling makes the code more reliable.
The above is the detailed content of How to Properly Handle Exceptions When Making REST API Calls in C#?. For more information, please follow other related articles on the PHP Chinese website!