WPF 使用 HttpClient 发送 POST 请求到 IIS 部署的 Web API
要在 WPF 中调用发布在 IIS 中的 Web API 的 POST 请求,你可以使用 HttpClient 类发送 HTTP 请求。下面是一个简单的示例代码:
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp
{
public class ApiClient
{
private readonly HttpClient _httpClient;
public ApiClient()
{
_httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri('http://localhost:5000'); // 替换为你的 Web API 的 URL
}
public async Task<string> PostDataAsync(string data)
{
var content = new StringContent(data, Encoding.UTF8, 'application/json');
var response = await _httpClient.PostAsync('/api/endpoint', content);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
throw new Exception($'HTTP request failed with status code {response.StatusCode}');
}
}
}
}
在上述代码中,ApiClient 类封装了发送 HTTP 请求的逻辑。你可以在 WPF 中的任何地方实例化 ApiClient 并调用 PostDataAsync 方法来发送 POST 请求。在 PostDataAsync 方法中,我们将数据转换为 JSON 字符串,并将其作为内容传递给 HttpClient 的 PostAsync 方法。你需要根据你的 Web API 的 URL 和端点路径进行相应的替换。
以下是一个在 WPF 窗口中使用 ApiClient 的示例:
using System.Windows;
using System.Threading.Tasks;
namespace WpfApp
{
public partial class MainWindow : Window
{
private ApiClient _apiClient;
public MainWindow()
{
InitializeComponent();
_apiClient = new ApiClient();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var data = '{'name': 'John', 'age': 30}'; // 你要发送的数据
try
{
var response = await _apiClient.PostDataAsync(data);
MessageBox.Show(response, 'API Response');
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, 'Error');
}
}
}
}
上述示例代码中,我们在 WPF 窗口的按钮点击事件处理程序中使用 ApiClient 来发送 POST 请求,并将响应显示在一个消息框中。
请注意,你需要将示例代码中的 URL 和数据进行相应的替换,以适应你的实际情况。
原文地址: https://www.cveoy.top/t/topic/qr4P 著作权归作者所有。请勿转载和采集!