
ASP.NET Web API快速入門介紹
REST是一種架構風格,利用HTTP協議中的GET、POST、PUT、DELETE等方法與服務器交互,通常用于客戶端和服務器之間的數據交換。REST API通信的核心在于定義資源,客戶端通過URL訪問服務器上的資源,并通過HTTP方法操作這些資源。
Boost 是一個廣受歡迎的 C++ 開源庫集合,提供了諸多用于跨平臺開發的實用工具。Boost 涵蓋了從算法到 I/O、正則表達式、容器和多線程等多種功能,尤其適合構建高性能的服務器、網絡和系統應用。我們就使用 Boost庫構建一個 RESTful 風格的 C++ Web API。
我們主要使用兩個核心庫:
通過vcpkg命令安裝 Boost.Asio庫
vcpkg install boost-asio
通過vcpkg命令安裝 Boost.Beast庫
vcpkg install boost-beast
使用 Boost.Beast 構建一個簡單的 RESTful API 服務,支持基本的 CRUD(創建、讀取、更新、刪除)操作。我們的 API 將運行在端口 8080
上,支持以下路徑:
GET /api/data
:獲取數據列表POST /api/data
:創建新數據PUT /api/data
:更新數據DELETE /api/data
:刪除數據#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <iostream>
#include <string>
#include <thread>
namespace asio = boost::asio;
namespace beast = boost::beast;
namespace http = beast::http;
using tcp = asio::ip::tcp;
std::string data_store = "Sample data"; // 簡單的數據存儲
// 處理 HTTP 請求的函數
void handle_request(const http::request<http::string_body>& req, http::response<http::string_body>& res) {
if (req.method() == http::verb::get && req.target() == "/api/data") {
res.result(http::status::ok);
res.set(http::field::content_type, "application/json");
res.body() = R"({"data": ")" + data_store + R"("})";
}
else if (req.method() == http::verb::post && req.target() == "/api/data") {
data_store = req.body();
res.result(http::status::created);
res.set(http::field::content_type, "application/json");
res.body() = R"({"message": "Data created"})";
}
else if (req.method() == http::verb::put && req.target() == "/api/data") {
data_store = req.body();
res.result(http::status::ok);
res.set(http::field::content_type, "application/json");
res.body() = R"({"message": "Data updated"})";
}
else if (req.method() == http::verb::delete_ && req.target() == "/api/data") {
data_store.clear();
res.result(http::status::ok);
res.set(http::field::content_type, "application/json");
res.body() = R"({"message": "Data deleted"})";
}
else {
res.result(http::status::not_found);
res.set(http::field::content_type, "application/json");
res.body() = R"({"error": "Resource not found"})";
}
res.prepare_payload();
}
// 會話處理
void session(tcp::socket socket) {
beast::flat_buffer buffer;
http::request<http::string_body> req;
http::response<http::string_body> res;
try {
http::read(socket, buffer, req);
handle_request(req, res);
http::write(socket, res);
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
// 主程序啟動服務器
int main() {
try {
asio::io_context ioc;
tcp::acceptor acceptor(ioc, tcp::endpoint(tcp::v4(), 8080));
std::cout << "Server running on http://localhost:8080\n";
while (true) {
tcp::socket socket(ioc);
acceptor.accept(socket);
std::thread(&session, std::move(socket)).detach();
}
} catch (const std::exception& e) {
std::cerr << "Server error: " << e.what() << std::endl;
}
return 0;
}
1.4 啟動服務程序
訪問地址:http://localhost:8080/
訪問地址:http://localhost:8080/api/data
使用 C# 的 HttpClient
調用 C++ RESTful API 并進行數據交互。
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace CppWebApiClient
{
class Program
{
private static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
// GET 請求
HttpResponseMessage response = await client.GetAsync("http://localhost:8080/api/data");
string getData = await response.Content.ReadAsStringAsync();
Console.WriteLine("GET Response: " + getData);
// POST 請求
string newData = "\"New sample data\"";
response = await client.PostAsync("http://localhost:8080/api/data", new StringContent(newData, Encoding.UTF8, "application/json"));
Console.WriteLine("POST Response: " + await response.Content.ReadAsStringAsync());
// PUT 請求
string updateData = "\"Updated data\"";
response = await client.PutAsync("http://localhost:8080/api/data", new StringContent(updateData, Encoding.UTF8, "application/json"));
Console.WriteLine("PUT Response: " + await response.Content.ReadAsStringAsync());
// DELETE 請求
response = await client.DeleteAsync("http://localhost:8080/api/data");
Console.WriteLine("DELETE Response: " + await response.Content.ReadAsStringAsync());
Console.ReadKey();
}
}
}
啟動客戶端程序
訪問地址:http://localhost:8080/api/data
數據已被刪除。
我們將通過兩個部分來構建一個RESTful風格的API服務(使用ASP.NET Core WebAPI)以及如何在C++中調用這個WebAPI。
dotnet new webapi -n MyApi
cd MyApi
2.?定義一個簡單的Controller?我們創建一個簡單的Controller?ProductsController.cs
,提供幾個GET和POST的接口
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace MyApi.Controllers
{
public class ProductRequest
{
public string Product { get; set; }
}
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
// 這是一個存儲產品的示例
private static readonly List<string> Products = new List<string>
{
"Product1",
"Product2",
"Product3"
};
// 獲取所有產品
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return Ok(Products);
}
// 獲取單個產品
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
if (id < 0 || id >= Products.Count)
{
return NotFound();
}
return Ok(Products[id]);
}
// 創建新產品
[HttpPost]
public ActionResult Post([FromBody] ProductRequest product)
{
if (string.IsNullOrEmpty(product?.Product))
{
return BadRequest("Product cannot be empty");
}
Products.Add(product.Product);
return CreatedAtAction(nameof(Get), new { id = Products.Count - 1 }, product);
}
}
}
3.?運行API?在命令行中,運行以下命令啟動API服務器:
dotnet run
現在,我們已經創建了一個基本的WebAPI服務。接下來,我們將在C++中編寫代碼,通過HTTP請求來調用這個WebAPI。為了發送HTTP請求,C++沒有內置的庫,因此我們將使用一些第三方庫,如libcurl
。
vcpkg install curl
2.?C++代碼:使用libcurl調用WebAPI在C++中,我們將使用libcurl
庫來發送HTTP請求。
#include <iostream>
#include <string>
#include <curl/curl.h>
// 回調函數,用于處理HTTP響應數據
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
size_t totalSize = size * nmemb;
((std::string*)userp)->append((char*)contents, totalSize);
return totalSize;
}
// GET請求
void GetProducts() {
CURL* curl;
CURLcode res;
std::string readBuffer;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:5056/api/products");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
// 執行請求
res = curl_easy_perform(curl);
// 檢查請求是否成功
if (res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
else {
std::cout << "Response: " << readBuffer << std::endl;
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
}
// POST請求
void AddProduct(const std::string& product) {
CURL* curl;
CURLcode res;
std::string readBuffer;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl) {
// 設置URL
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:5056/api/products");
// 設置HTTP頭
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
// 設置POST數據
std::string jsonData = "{\"product\":\"" + product + "\"}";
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonData.c_str());
// 處理響應
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
// 執行請求
res = curl_easy_perform(curl);
// 檢查請求是否成功
if (res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
else {
std::cout << "Response: " << readBuffer << std::endl;
}
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
}
curl_global_cleanup();
}
int main() {
// 獲取所有產品
GetProducts();
// 添加新產品
AddProduct("Product4");
// 獲取所有產品,查看是否添加成功
GetProducts();
int i;
std::cin >> i;
return 0;
}
3.?編譯并運行C++代碼
REST API 提供了一種靈活且標準化的通信方式,能夠在不同語言和平臺間實現通信。通過本文的示例代碼,C++ 和 C# 程序可以借助 REST API 實現數據交互。這種方法尤其適合分布式應用和微服務架構的設計。在下一篇中,我們將介紹gRPC,這是一個高效的跨平臺通信協議,非常適合高性能需求的場景。
文章轉自微信公眾號@dotnet研習社