在C#中使用WebAssembly處理網絡請求時,可以利用HTML5的Fetch API或者JavaScript橋接庫(如JavaScript Interop)來實現。以下是一個使用Fetch API的示例:
network.js),并添加以下內容:window.fetch = (url, options) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(options.method || 'GET', url);
xhr.setRequestHeader('Content-Type', options.headers ? options.headers['Content-Type'] : 'application/json');
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(new Error(`Request failed with status ${xhr.status}`));
}
};
xhr.onerror = () => {
reject(new Error('Network error'));
};
if (options.body) {
xhr.send(JSON.stringify(options.body));
} else {
xhr.send();
}
});
};
這段代碼定義了一個fetch函數,用于發送HTTP請求。請注意,這里使用了原生的XMLHttpRequest對象,因為WebAssembly目前沒有內置的Fetch API支持。
NetworkClient.cs),并添加以下內容:using System;
using System.Runtime.InteropServices;
public static class NetworkClient
{
[DllImport("__Internal")]
private static extern void RegisterFetchApi();
[DllImport("__Internal")]
private static extern dynamic Fetch(string url, dynamic options);
static NetworkClient()
{
RegisterFetchApi();
}
public static async Task<dynamic> GetAsync(string url)
{
return await InvokeFetchAsync("GET", url, null);
}
public static async Task<dynamic> PostAsync(string url, dynamic data)
{
return await InvokeFetchAsync("POST", url, data);
}
private static async Task<dynamic> InvokeFetchAsync(string method, string url, dynamic options)
{
dynamic jsonOptions = options != null ? Newtonsoft.Json.JsonConvert.SerializeObject(options) : null;
dynamic result = await Fetch(url, jsonOptions);
return result;
}
}
這個類使用P/Invoke調用JavaScript的fetch函數,并提供了一些靜態方法來簡化網絡請求。
Program.cs文件中,調用NetworkClient類來發送網絡請求:using System;
using System.Threading.Tasks;
namespace WebAssemblyApp
{
public class Program
{
public static async Task Main(string[] args)
{
string url = "https://api.example.com/data";
dynamic data = await NetworkClient.GetAsync(url);
Console.WriteLine(data);
}
}
}
這個示例展示了如何使用C# WebAssembly和JavaScript互操作類發送一個GET請求。你可以根據需要修改這個示例,以支持其他HTTP方法和請求頭。