Câu hỏi:

code c# restful api bằng thư viện restclient và cấu trúc như dự án thật


Trước tiên, bạn nên cài đặt thư viện RestClient bằng NuGet. Để làm điều này, bạn có thể sử dụng Package Manager Console với lệnh sau:

Install-Package RestSharp

Tiếp theo, bạn có thể tạo một dự án C# mới và tạo các thư mục và class cần thiết để cấu trúc dự án theo mô hình sau:

- ProjectName
- Controllers
- ApiController.cs
- Models
- RequestModel.cs
- ResponseModel.cs
- Services
- ApiService.cs
- Program.cs

Sau đó, hãy thêm mã sau cho các tệp:

  1. ApiController.cs:
using System;
using ProjectName.Models;
using ProjectName.Services;

namespace ProjectName.Controllers
{
public class ApiController
{
private readonly ApiService _apiService;

public ApiController()
{
_apiService = new ApiService();
}

public void CallApi(RequestModel request)
{
try
{
ResponseModel response = _apiService.PerformApiCall(request);
Console.WriteLine($"Status: {response.Status}, Message: {response.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}
  1. RequestModel.cs:
namespace ProjectName.Models
{
public class RequestModel
{
public string Url { get; set; }
public string HttpMethod { get; set; }
}
}
  1. ResponseModel.cs:
namespace ProjectName.Models
{
public class ResponseModel
{
public int Status { get; set; }
public string Message { get; set; }
}
}
  1. ApiService.cs:
using System;
using RestSharp;
using ProjectName.Models;

namespace ProjectName.Services
{
public class ApiService
{
public ResponseModel PerformApiCall(RequestModel request)
{
try
{
RestClient client = new RestClient(request.Url);
RestRequest restRequest = new RestRequest((Method)Enum.Parse(typeof(Method), request.HttpMethod));

IRestResponse restResponse = client.Execute(restRequest);

return new ResponseModel
{
Status = (int)restResponse.StatusCode,
Message = restResponse.Content
};
}
catch (Exception ex)
{
throw new ApplicationException($"Error in performing API call: {ex.Message}");
}
}
}
}
  1. Cuối cùng, hãy thêm mã sau cho tệp Program.cs để kiểm tra chương trình:
using System;
using ProjectName.Controllers;
using ProjectName.Models;

namespace ProjectName
{
class Program
{
static void Main(string[] args)
{
ApiController apiController = new ApiController();

RequestModel request = new RequestModel
{
Url = "https://jsonplaceholder.typicode.com/posts/1",
HttpMethod = "GET"
};

apiController.CallApi(request);

Console.ReadLine();
}
}
}

Bạn có thể thay đổi URL và HttpMethod trong ví dụ trên để kiểm tra với các API khác.


Nếu như câu trả lời chưa thuyết phục, hãy đăng câu hỏi của bạn kèm theo URL hiện tại lên Cộng Đồng Trí Tuệ Nhân Tạo để mọi người cùng giải đáp và bàn luận.
Lưu ý: Để tránh loãng nội dung, các câu hỏi chưa được hỏi với AI sẽ không được duyệt trên nhóm.
Trang chủ | Hỏi tiếp | Xem lịch sử