在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中的webapi

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

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