在线做投资网站小程序注册量
2026/1/15 11:56:02 网站建设 项目流程
在线做投资网站,小程序注册量,广西钦州网站建设,电商运营平台一、项目整体结构该项目是一个基于 WPF 的 HTTPS 通信演示程序#xff0c;采用 MVVM 设计模式#xff0c;主要实现了 GET/POST/PUT/DELETE 四种 HTTP 请求的发送#xff0c;并展示响应结果。项目分为三个核心部分#xff1a;模型层#xff08;Model#xff09;#xff1…一、项目整体结构该项目是一个基于 WPF 的 HTTPS 通信演示程序采用 MVVM 设计模式主要实现了 GET/POST/PUT/DELETE 四种 HTTP 请求的发送并展示响应结果。项目分为三个核心部分模型层Model定义请求和响应的数据结构视图模型层ViewModel处理业务逻辑实现数据绑定和命令绑定视图层ViewMainWindow.xaml负责 UI 展示二、模型层Model代码分析1. 功能说明定义HttpRequestModelHTTP 请求模型和HttpResponseModelHTTP 响应模型封装请求 / 响应的核心属性提供默认构造函数初始化默认值。2. 核心代码using System; using System.Collections.Generic; ​ namespace HttpsDemoApp.Model { // HTTP请求模型封装请求的URL、方法、请求体、请求头 public class HttpRequestModel { public string Url { get; set; } public string Method { get; set; } public string RequestBody { get; set; } public Dictionarystring, string Headers { get; set; } ​ // 构造函数初始化请求头字典默认请求方法为GET public HttpRequestModel() { Headers new Dictionarystring, string(); Method GET; } } ​ // HTTP响应模型封装响应的状态码、状态信息、响应内容、响应头、响应时间 public class HttpResponseModel { public int StatusCode { get; set; } public string StatusMessage { get; set; } public string Content { get; set; } public Dictionarystring, string Headers { get; set; } public DateTime ResponseTime { get; set; } ​ // 构造函数初始化响应头字典默认响应时间为当前时间 public HttpResponseModel() { Headers new Dictionarystring, string(); ResponseTime DateTime.Now; } } }3. 关键要点HttpRequestModel默认方法为 GET请求头初始化为空字典HttpResponseModel响应时间默认取当前时间响应头初始化为空字典采用Dictionarystring, string存储请求 / 响应头便于键值对管理三、视图模型层ViewModel代码分析1. 功能说明实现MainViewModel核心视图模型和RelayCommand命令绑定实现处理 HTTP 请求发送逻辑实现INotifyPropertyChanged接口支持数据双向绑定。2. 核心代码MainViewModelusing HttpsDemoApp.Model; using System; using System.ComponentModel; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows.Input; ​ namespace HttpsDemoApp.ViewModel { // 主视图模型实现INotifyPropertyChanged支持属性变更通知 public class MainViewModel : INotifyPropertyChanged { // 私有字段 private string _url; private string _method; private string _requestBody; private string _responseContent; private bool _isLoading; private HttpResponseModel _response; ​ // 属性变更事件 public event PropertyChangedEventHandler PropertyChanged; ​ // 公开属性带变更通知 public string Url { get { return _url; } set { _url value; OnPropertyChanged(nameof(Url)); } } ​ public string Method { get { return _method; } set { _method value; OnPropertyChanged(nameof(Method)); } } ​ public string RequestBody { get { return _requestBody; } set { _requestBody value; OnPropertyChanged(nameof(RequestBody)); } } ​ public string ResponseContent { get { return _responseContent; } set { _responseContent value; OnPropertyChanged(nameof(ResponseContent)); } } ​ public bool IsLoading { get { return _isLoading; } set { _isLoading value; OnPropertyChanged(nameof(IsLoading)); } } ​ public HttpResponseModel Response { get { return _response; } set { _response value; OnPropertyChanged(nameof(Response)); } } ​ // 发送请求命令 public ICommand SendRequestCommand { get; private set; } ​ // 构造函数初始化默认值绑定命令 public MainViewModel() { Url https://jsonplaceholder.typicode.com/posts/1; // 测试URL Method GET; RequestBody ; ResponseContent ; IsLoading false; SendRequestCommand new RelayCommand(async param await SendRequestAsync()); } ​ // 属性变更通知方法 protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } ​ // 异步发送HTTP请求核心方法 private async Task SendRequestAsync() { IsLoading true; ResponseContent 正在发送请求...; ​ try { using (var httpClient new HttpClient()) { HttpResponseMessage response null; ​ // 根据请求方法执行不同操作 switch (Method.ToUpper()) { case GET: response await httpClient.GetAsync(Url); break; case POST: var content new StringContent(RequestBody, Encoding.UTF8, application/json); response await httpClient.PostAsync(Url, content); break; case PUT: var putContent new StringContent(RequestBody, Encoding.UTF8, application/json); response await httpClient.PutAsync(Url, putContent); break; case DELETE: response await httpClient.DeleteAsync(Url); break; } ​ // 处理响应结果 if (response ! null) { var responseModel new HttpResponseModel { StatusCode (int)response.StatusCode, StatusMessage response.ReasonPhrase, Content await response.Content.ReadAsStringAsync(), ResponseTime DateTime.Now }; ​ // 解析响应头 foreach (var header in response.Headers) { responseModel.Headers.Add(header.Key, string.Join(, , header.Value)); } ​ Response responseModel; // 格式化响应内容展示 ResponseContent $状态码: {responseModel.StatusCode} {responseModel.StatusMessage}\n\n $响应时间: {responseModel.ResponseTime}\n\n $响应内容:\n{responseModel.Content}; } } } catch (HttpRequestException ex) { // HTTP请求异常处理 ResponseContent $HTTP 请求异常: {ex.Message}\n\n $Inner Exception: {ex.InnerException?.Message}; } catch (Exception ex) { // 通用异常处理 ResponseContent $异常: {ex.Message}\n\n $Stack Trace: {ex.StackTrace}; } finally { IsLoading false; // 无论是否异常最终结束加载状态 } } } }3. 核心代码RelayCommand// 命令实现类支持异步执行的RelayCommand public class RelayCommand : ICommand { private readonly Funcobject, Task _execute; private readonly Funcobject, bool _canExecute; ​ public event EventHandler CanExecuteChanged; ​ // 构造函数初始化执行方法和可执行判断方法 public RelayCommand(Funcobject, Task execute, Funcobject, bool canExecute null) { _execute execute ?? throw new ArgumentNullException(nameof(execute)); _canExecute canExecute; } ​ // 判断命令是否可执行 public bool CanExecute(object parameter) { return _canExecute null || _canExecute(parameter); } ​ // 执行命令异步 public async void Execute(object parameter) { await _execute(parameter); } ​ // 触发可执行状态变更 public void RaiseCanExecuteChanged() { CanExecuteChanged?.Invoke(this, EventArgs.Empty); } }4. 关键要点1MVVM 核心特性实现INotifyPropertyChanged接口通过OnPropertyChanged方法触发属性变更通知使 UI 自动更新命令绑定通过RelayCommand将按钮点击事件绑定到SendRequestAsync方法异步处理使用async/await处理 HTTP 请求避免 UI 线程阻塞2HTTP 请求处理支持 GET/POST/PUT/DELETE 四种方法POST/PUT 默认使用 JSON 格式请求体UTF8 编码使用HttpClient发送请求通过using语句自动释放资源异常处理区分HttpRequestExceptionHTTP 相关异常和通用异常友好展示错误信息3状态管理IsLoading控制加载进度条显示请求发送时设为 true结束后设为 false响应结果格式化将状态码、响应时间、响应内容拼接展示在ResponseContent中四、视图层View代码分析1. 功能说明MainWindow.xaml 作为 UI 界面通过数据绑定关联 ViewModel 的属性和命令实现用户交互和结果展示。2. 核心代码Window x:ClassHttpsDemoApp.MainWindow xmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentation xmlns:xhttp://schemas.microsoft.com/winfx/2006/xaml xmlns:dhttp://schemas.microsoft.com/expression/blend/2008 xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006 xmlns:localclr-namespace:HttpsDemoApp xmlns:vmclr-namespace:HttpsDemoApp.ViewModel mc:Ignorabled TitleWPF HTTPS 通信示例 Height600 Width900 Window.Resources !-- 布尔值转可见性转换器 -- BooleanToVisibilityConverter x:KeyBoolToVisibilityConverter / !-- 自定义布尔值反转转换器需实现 -- local:BoolToInverseBoolConverter x:KeyBoolToInverseBoolConverter / /Window.Resources !-- 绑定视图模型作为数据上下文 -- Window.DataContext vm:MainViewModel / /Window.DataContext Grid Margin10 Grid.RowDefinitions RowDefinition HeightAuto / RowDefinition HeightAuto / RowDefinition Height* / RowDefinition HeightAuto / /Grid.RowDefinitions Grid.ColumnDefinitions ColumnDefinition Width* / ColumnDefinition Width100 / /Grid.ColumnDefinitions ​ !-- URL输入框 -- Grid Grid.Row0 Grid.Column0 Grid.ColumnSpan2 Margin0,0,0,10 Grid.ColumnDefinitions ColumnDefinition WidthAuto / ColumnDefinition Width* / /Grid.ColumnDefinitions Label ContentURL: VerticalAlignmentCenter Margin0,0,10,0 / TextBox Text{Binding Url} Grid.Column1 Height30 VerticalContentAlignmentCenter / /Grid ​ !-- 请求方法选择和发送按钮 -- Grid Grid.Row1 Grid.Column0 Grid.ColumnSpan2 Margin0,0,0,10 Grid.ColumnDefinitions ColumnDefinition WidthAuto / ColumnDefinition Width100 / ColumnDefinition Width* / ColumnDefinition Width100 / /Grid.ColumnDefinitions Label Content方法: VerticalAlignmentCenter Margin0,0,10,0 / ComboBox SelectedValue{Binding Method} SelectedValuePathContent Grid.Column1 Height30 ComboBoxItem ContentGET / ComboBoxItem ContentPOST / ComboBoxItem ContentPUT / ComboBoxItem ContentDELETE / /ComboBox !-- 发送按钮绑定命令加载时禁用 -- Button Content发送请求 Grid.Column3 Height30 Command{Binding SendRequestCommand} IsEnabled{Binding IsLoading, Converter{StaticResource BoolToInverseBoolConverter}} / /Grid ​ !-- 请求体输入框 -- Grid Grid.Row2 Grid.Column0 Margin0,0,0,9.667 HorizontalAlignmentLeft Width402 Grid.RowDefinitions RowDefinition HeightAuto / RowDefinition Height* / /Grid.RowDefinitions Label Content请求体: Margin0,0,0,5 / TextBox Text{Binding RequestBody} Grid.Row1 AcceptsReturnTrue TextWrappingWrap VerticalScrollBarVisibilityAuto Margin0,0.333,-52,-0.333 / /Grid ​ !-- 响应内容展示框 -- Grid Grid.Row2 Grid.Column1 Margin0,0,0,10 Grid.RowDefinitions RowDefinition HeightAuto / RowDefinition Height20* / RowDefinition Height23*/ /Grid.RowDefinitions Label Content响应: Margin0,0,0,4.667 / TextBox Text{Binding ResponseContent} Grid.Row1 IsReadOnlyTrue AcceptsReturnTrue TextWrappingWrap VerticalScrollBarVisibilityAuto Margin-307,0,0,-0.333 Grid.RowSpan2 / /Grid ​ !-- 加载进度条 -- Grid Grid.Row3 Grid.Column0 Grid.ColumnSpan2 ProgressBar IsIndeterminate{Binding IsLoading} Height10 Visibility{Binding IsLoading, Converter{StaticResource BoolToVisibilityConverter}}/ProgressBar /Grid /Grid /Window3. 关键要点1数据绑定Window.DataContext绑定MainViewModel作为整个窗口的数据上下文控件绑定URL 输入框Text{Binding Url}请求方法下拉框SelectedValue{Binding Method}请求体输入框Text{Binding RequestBody}响应内容展示框Text{Binding ResponseContent}只读发送按钮Command{Binding SendRequestCommand}2转换器使用BooleanToVisibilityConverter将IsLoadingbool转为进度条的可见性VisibilityBoolToInverseBoolConverter反转IsLoading值实现加载时禁用发送按钮需补充实现该转换器类3UI 布局采用 Grid 布局分行列管理控件位置适配窗口大小请求体和响应内容使用多行文本框AcceptsReturnTrue支持换行和滚动条五、补充说明缺失的转换器实现代码中引用了BoolToInverseBoolConverter但未实现需补充using System; using System.Globalization; using System.Windows.Data; ​ namespace HttpsDemoApp { public class BoolToInverseBoolConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool boolValue) { return !boolValue; } return false; } ​ public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool boolValue) { return !boolValue; } return false; } } }六、整体总结1. 设计模式MVVM 模式分离 UIView、业务逻辑ViewModel、数据Model降低耦合命令模式通过RelayCommand实现 UI 操作与业务逻辑的解耦2. 核心特性异步 HTTP 请求避免 UI 阻塞提升用户体验数据双向绑定属性变更自动同步到 UIUI 输入自动同步到 ViewModel异常处理区分不同类型异常友好展示错误信息状态管理加载状态控制进度条和按钮可用状态3. 改进建议增加请求头自定义功能当前 Model 支持但 UI 未实现优化响应内容格式化如 JSON 格式化展示添加请求超时设置HttpClient.Timeout增加请求参数验证如 URL 格式校验完善日志记录便于调试

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询