要在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字符串,并将其作为内容传递给HttpClientPostAsync方法。你需要根据你的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和数据进行相应的替换,以适应你的实际情况

WPF调用发布在iis中的webapi的post请求

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

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