在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方法和请求头。