在 WPF 中调用发布在 IIS 中的 WebAPI,可以使用 HttpClient 类发送 HTTP 请求来调用 WebAPI 的接口。

首先,在 WPF 项目中添加对 System.Net.Http 命名空间的引用。然后,创建一个 HttpClient 对象来发送 HTTP 请求:

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

public class ApiClient
{
    private readonly HttpClient _httpClient;

    public ApiClient()
    {
        _httpClient = new HttpClient();
        _httpClient.BaseAddress = new Uri('http://localhost:port/'); // 替换成你的 WebAPI 的地址
    }

    public async Task<string> Get(string url)
    {
        HttpResponseMessage response = await _httpClient.GetAsync(url);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }

    public async Task<string> Post(string url, object data)
    {
        HttpResponseMessage response = await _httpClient.PostAsJsonAsync(url, data);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }
}

接下来,在 WPF 的代码中创建 ApiClient 对象,并调用 Get 或 Post 方法来调用 WebAPI 的接口。例如:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    ApiClient apiClient = new ApiClient();
    string result = await apiClient.Get('api/your-api-url'); // 替换成你的 WebAPI 的接口 URL
    // 处理返回的结果
}

请注意,这里的 'http://localhost:port/' 是你的 WebAPI 的地址,其中的 'port' 是你的 IIS 的端口号。另外,'api/your-api-url' 是你的 WebAPI 的接口 URL,根据你的 WebAPI 的配置来进行替换。

WPF 调用 IIS 发布的 Web API

原文地址: https://www.cveoy.top/t/topic/qr0w 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录