要在 WPF 中调用发布在 IIS 中的 Web API,您可以执行以下步骤:

  1. 在 WPF 项目中创建一个新的类(例如 ApiService),用于处理与 Web API 的通信。
  2. 在 ApiService 类中,使用 HttpClient 类来发送 HTTP 请求并接收响应。例如:
using System.Net.Http;
using System.Threading.Tasks;

public class ApiService
{
    private HttpClient client;

    public ApiService()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri('http://localhost:port/'); // 将端口替换为您的 Web API 所在的端口号
    }

    public async Task<string> GetApiResponse(string endpoint)
    {
        HttpResponseMessage response = await client.GetAsync(endpoint);
        response.EnsureSuccessStatusCode(); // 确保响应成功

        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }
}
  1. 在需要调用 Web API 的地方,创建 ApiService 实例并调用 GetApiResponse 方法。例如:
public async Task CallWebApi()
{
    ApiService apiService = new ApiService();
    string response = await apiService.GetApiResponse('api/endpoint'); // 将 'api/endpoint' 替换为您的 Web API 的实际端点

    // 处理响应
}

请注意,上述示例中的端口号应替换为您的 Web API 实际运行的端口号,以及 'api/endpoint' 应替换为您的 Web API 的实际端点。

WPF 调用发布在 IIS 中的 Web API

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

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