当前位置: 首页 > news >正文

WPF call webHttpBinding from WCF

//WCF
//D:\C\WcfService4\WcfService4\Web.config
<?xml version="1.0"?>
<configuration><appSettings><add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /></appSettings><system.web><compilation debug="true" targetFramework="4.8" /><httpRuntime targetFramework="4.8" maxRequestLength="2147483647"/></system.web><system.serviceModel><services><service name="WcfService4.BookService"><endpoint address=""binding="webHttpBinding"bindingConfiguration="WebHttpBinding_IBookSerive"behaviorConfiguration="webBehavior_test"contract="WcfService4.IBookService"/><host><baseAddresses><add baseAddress="http://localhost:8080"/></baseAddresses></host></service></services><bindings><webHttpBinding><binding name="WebHttpBinding_IBookSerive"maxBufferPoolSize="2147483647"maxReceivedMessageSize="2147483647"><readerQuotasmaxDepth="2147483647"maxStringContentLength="2147483647"maxArrayLength="2147483647"maxBytesPerRead="2147483647"maxNameTableCharCount="2147483647"/></binding></webHttpBinding></bindings><behaviors><endpointBehaviors><behavior name="webBehavior_test"><webHttp/></behavior></endpointBehaviors><serviceBehaviors><behavior><!-- To avoid disclosing metadata information, set the values below to false before deployment --><serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/><!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information --><serviceDebug includeExceptionDetailInFaults="true"/></behavior></serviceBehaviors></behaviors><serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /></system.serviceModel><system.webServer><modules runAllManagedModulesForAllRequests="true"/><rewrite><rules><rule name="WCF Without SVC" stopProcessing="true"><match url="^(.*)$"/><conditions logicalGrouping="MatchAll"><add input="{REQUEST_FILENAME}" matchType="IsFile"negate="true"/><add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/></conditions><action type="Rewrite" url="BookService.svc/{R:1}"/></rule></rules></rewrite><directoryBrowse enabled="true"/></system.webServer>
</configuration>//D:\C\WcfService4\WcfService4\IBookService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;namespace WcfService4
{// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IBookService" in both code and config file together.
    [ServiceContract]public interface IBookService{[OperationContract][WebGet(UriTemplate="GetBooksList?cnt={cnt}",RequestFormat =WebMessageFormat.Json, ResponseFormat =WebMessageFormat.Json)]List<Book> GetBooksList(int cnt);}[DataContract]public class Book{[DataMember(IsRequired = true,Order =1)]public long Id { get; set; }[DataMember(IsRequired = true, Order = 2)]public string Author { get; set; }[DataMember(IsRequired = true, Order = 3)]public string Abstract { get; set; }[DataMember(IsRequired = true, Order = 4)]public string Name { get; set; }[DataMember(IsRequired = true, Order = 5)]public string ISBN {  get; set; }[DataMember(IsRequired = true, Order = 6)]public string Title {  get; set; }[DataMember(IsRequired = true, Order = 7)]public string Topic {  get; set; }[DataMember(IsRequired =true, Order = 8)]public string Comment { get; set;  }[DataMember(IsRequired =true,Order = 9)]public string Content { get; set; }[DataMember(IsRequired =true,Order =10)]public string Summary {  get; set; }}
}//D:\C\WcfService4\WcfService4\BookService.svc.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading;namespace WcfService4
{// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "BookService" in code, svc and config file together.// NOTE: In order to launch WCF Test Client for testing this service, please select BookService.svc or BookService.svc.cs at the Solution Explorer and start debugging.public class BookService : IBookService{private static long idx = 0;private long GetIncrementIdx(){return Interlocked.Increment(ref idx);}public List<Book> GetBooksList(int cnt){List<Book> bksList = new List<Book>();for (int i = 0; i < cnt; i++){long a = GetIncrementIdx();bksList.Add(new Book(){Id = a,Name = $"Name_{a}",ISBN = $"ISBN_{a}",Comment = $"Comment_{a}",Content = $"Content_{a}",Summary = $"Summary_{a}",Author = $"Author_{a}",Abstract = $"Abstract_{a}",Title = $"Title_{a}",Topic = $"Topic_{a}"});}return bksList;}}
}

 

 

WPF

Install-Package Newtonsoft.json

 

 

<Window x:Class="WpfApp27.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfApp27"mc:Ignorable="d"Title="{Binding MainTitle}"WindowState="Maximized"><Window.DataContext><local:MainVM/></Window.DataContext><Grid><DataGrid ItemsSource="{Binding BooksCollection}"VirtualizingPanel.IsVirtualizing="True"VirtualizingPanel.VirtualizationMode="Recycling"VirtualizingPanel.CacheLength="5,5"VirtualizingPanel.CacheLengthUnit="Item"ScrollViewer.CanContentScroll="True"ScrollViewer.IsDeferredScrollingEnabled="True"UseLayoutRounding="True"SnapsToDevicePixels="True"EnableColumnVirtualization="True"EnableRowVirtualization="True"AutoGenerateColumns="True"CanUserAddRows="False"><DataGrid.Resources><Style TargetType="DataGridRow"><Setter Property="FontSize" Value="30"/><Style.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter Property="FontSize" Value="50"/><Setter Property="Foreground" Value="Red"/></Trigger></Style.Triggers></Style></DataGrid.Resources></DataGrid></Grid>
</Window>using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;namespace WpfApp27
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}}public class MainVM : INotifyPropertyChanged{HttpClient client;DispatcherTimer tmr;string url = "http://localhost:55548/getbookslist?cnt=1000000";public MainVM(){client = new HttpClient();Task.Run(async () =>{await DownloadHttpJsonAsync();});tmr = new DispatcherTimer();tmr.Interval = TimeSpan.FromSeconds(10);tmr.Tick += async (s, e) =>{await DownloadHttpJsonAsync();};tmr.Start();}private async Task DownloadHttpJsonAsync(){try{string jsonStr = await client.GetStringAsync(url);if (!string.IsNullOrWhiteSpace(jsonStr)){var booksList = JsonConvert.DeserializeObject<List<Book>>(jsonStr);if (booksList != null && booksList.Any()){BooksCollection = new ObservableCollection<Book>(booksList);MainTitle = $"{DateTime.Now},loaded {BooksCollection.Count()} books,first id:{BooksCollection.FirstOrDefault().Id},Last Id:{BooksCollection.LastOrDefault().Id}";}}}catch (Exception ex){MessageBox.Show($"{ex.Message}", $"{DateTime.Now}");                 }            }private string mainTitle = $"{DateTime.Now},loading...";public string MainTitle{get{return mainTitle;}set{if(value!= mainTitle){mainTitle = value;OnPropertyChanged();}}}private ObservableCollection<Book> booksCollection;public ObservableCollection<Book> BooksCollection{get{return booksCollection;}set{if(value!=booksCollection){booksCollection = value;OnPropertyChanged();}}}public event PropertyChangedEventHandler? PropertyChanged;private void OnPropertyChanged([CallerMemberName]string propName=""){var handler = PropertyChanged;handler?.Invoke(this, new PropertyChangedEventArgs(propName));}}[DataContract]public class Book{[DataMember(IsRequired = true, Order = 1)]public long Id { get; set; }[DataMember(IsRequired = true, Order = 2)]public string Author { get; set; }[DataMember(IsRequired = true, Order = 3)]public string Abstract { get; set; }[DataMember(IsRequired = true, Order = 4)]public string Name { get; set; }[DataMember(IsRequired = true, Order = 5)]public string ISBN { get; set; }[DataMember(IsRequired = true, Order = 6)]public string Title { get; set; }[DataMember(IsRequired = true, Order = 7)]public string Topic { get; set; }[DataMember(IsRequired = true, Order = 8)]public string Comment { get; set; }[DataMember(IsRequired = true, Order = 9)]public string Content { get; set; }[DataMember(IsRequired = true, Order = 10)]public string Summary { get; set; }}}

 

 

 

 

 

image

 

 

image

 

 

image

 

http://www.jsqmd.com/news/753347/

相关文章:

  • Arm CoreLink CI-700缓存一致性互连架构与优化实践
  • 从毛玻璃到亚克力:用Qt 6.5在Windows 11上实现现代化半透明UI效果
  • 你的Python项目依赖真的干净吗?从‘packaging‘缺失聊聊pyproject.toml和现代包管理
  • cppm证书到底要不要考?含金量怎么样?全在这了 - 众智商学院课程中心
  • Win2008 R2靶场搭建与渗透保姆级复盘:DedeCMS、phpMyAdmin那些年我们踩过的坑
  • 深入浅出:大语言模型 Agent 的工作原理与应用
  • 长期使用 Taotoken 聚合 API 对项目运维复杂度的实际降低感受
  • 丁于洲博士受聘上海中医药大学平顶山医院中医临床特聘专家
  • 2026 全国防水公司 TOP5 权威排名 - 防水百科
  • 基于Godot引擎的FPS游戏框架:模块化设计与核心系统实现
  • RT-Thread Studio里那个不起眼的‘RT-Thread Settings’,到底藏了多少宝藏?
  • 别再只盯着LVS报错!从版图到网表的‘翻译’过程,才是芯片设计不翻车的核心
  • 2026年4月市场专业的报告自动生成企业口碑推荐,制造业实验室管理系统/实验室智能化,报告自动生成企业找哪家 - 品牌推荐师
  • 抖音内容获取架构解析:模块化下载器的设计哲学与实践
  • 从2D地图到3D地球:用Cesium Entities API 快速构建你的第一个三维地理围栏(附完整代码)
  • 2026年目前消防泵直销厂家,排污泵/稳压泵/无负压供水设备/玻璃钢水箱/恒压变频供水设备/软化水箱,消防泵厂家哪家好 - 品牌推荐师
  • AI Agent 与 MCP 协议:构建标准化大模型交互的新范式
  • 2026年4月优秀的管线管品牌口碑推荐,Q355E无缝钢管/高温高压锅炉管/锅炉管,管线管源头厂家推荐 - 品牌推荐师
  • 告别卡顿!手把手教你用Linux解包修改Android手机的vendor.img,精简预装App
  • WCF binding webHttpBinding is used to web browser in json format both in request and response
  • 2026届必备的降重复率网站横评
  • A08.使用WAF对金戈企业网站进行安全防护
  • 罗技PUBG鼠标宏压枪脚本:快速提升射击精准度的终极指南
  • 别再傻傻print了!用tqdm给你的Python脚本加个进度条(附Jupyter Notebook实战)
  • LangChain RAG开发套件:集成多模型与高级检索的快速构建指南
  • 新手工程师必看:手把手教你搞定TMS320F280049最小系统电源与晶振设计(附原理图)
  • 创业团队如何利用 Taotoken 多模型能力优化产品 AI 功能
  • GD32F103 SysTick定时器实战:从轮询到中断,两种延时方案怎么选?
  • GAC-KAN:边缘AI时代的轻量级GNSS干扰分类方案
  • 保姆级教程:用STM32F103和CubeMX实现汽车电池监控CAN通讯(附完整工程下载)