引言
实现步骤
1. 创建 WebApi 项目
2. 定义 WebApi 控制器
csharp
using System;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class ClientInfoController : ControllerBase
{
[HttpGet]
public ActionResult<string> GetClientInfo()
{
var request = HttpContext.Request;
var ipAddress = request.Host.Host ?? "Unknown";
var userAgent = request.Headers["User-Agent"].ToString();
var requestUrl = request.Path.Value ?? "Not provided";
var requestMethod = request.Method;
var queryString = request.QueryString.Value;
string clientInfo = $"客户端IP地址: {ipAddress}\n" +
$"User-Agent: {userAgent}\n" +
$"请求URL: {requestUrl}\n" +
$"请求方法: {requestMethod}\n" +
$"查询字符串: {queryString}";
return Ok(clientInfo);
}
}
3. 创建 WPF 客户端应用程序
打开 Visual Studio,创建一个新的 WPF 应用程序项目。
在 WPF 项目中,添加对
System.Net.Http
的引用。创建一个按钮,当点击时,使用
HttpClient
调用 WebApi 并获取客户端信息。
xaml
<Button x:Name="GetInfoButton" Content="获取客户端信息" Click="GetInfoButton_Click" />
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
namespace WpfClientApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void GetInfoButton_Click(object sender, RoutedEventArgs e)
{
HttpClient client = new HttpClient();
string result = await client.GetStringAsync("http://localhost:port/api/ClientInfo");
MessageBox.Show(result);
}
}
}
4. 运行和测试
结论
往期精品推荐: