温馨提示×

c# wasm如何调用Web API

c#
小樊
86
2024-07-23 21:47:06
栏目: 编程语言

要在C#的Wasm中调用Web API,可以使用HttpClient类来发送HTTP请求并接收响应。以下是一个简单的示例代码:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var httpClient = new HttpClient();
        
        HttpResponseMessage response = await httpClient.GetAsync("https://api.example.com/data");
        
        if(response.IsSuccessStatusCode)
        {
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
    }
}

在上面的代码中,我们首先创建了一个HttpClient实例,然后使用GetAsync方法发送一个GET请求到指定的API地址。接着,我们检查响应是否成功,并读取响应内容以打印到控制台。

请注意,由于Wasm的沙盒环境限制,可能需要在Wasm项目的manifest文件中添加网络访问权限,例如:

<Capability Name="InternetClient" />
<Capability Name="InternetClientServer" />

这样就可以在C#的Wasm项目中调用Web API了。

0