Home > Backend Development > C++ > How Can I Use C# to Consume REST APIs and Handle Potential Exceptions?

How Can I Use C# to Consume REST APIs and Handle Potential Exceptions?

Linda Hamilton
Release: 2025-01-25 14:57:11
Original
889 people have browsed it

How Can I Use C# to Consume REST APIs and Handle Potential Exceptions?

C# REST API calling method

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>
Copy after login

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>
Copy after login

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 ExceptionBase 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template