WPF内嵌WCF服务对外提供接口

要测试本帖子代码请记得管理员权限运行vs。

我写这个帖子的初衷是在我做surface小车的时候有类似的需求,感觉这个功能还挺有意思的,所以就分享给大家,网上有很多关于wcf的文章 我就不一一列举了。公司有个旧的项目是winform写的,里面就有这个内嵌的wcf,我还没怎么搞过wpf,大家都说winform太老了,于是乎我就想用wpf内嵌下试试看看能不能成功。

下面是我的surface go小车的帖子。

 https://www.cnblogs.com/GreenShade/p/10912738.html

 

这个项目我是参考网上的一个帖子。不过好多网友的贴子或多或少都有帮助,但是有的没收藏下来。我就贴上一个我觉得是干货的帖子吧。

 .https://social.msdn.microsoft.com/forums/silverlight/en-US/d7afa073-e329-43a7-a120-7c59e1a4fd7f/how-to-return-html-page-from-wcf-with-webhttpbinding

首先我们要确保vs里面安装了wcf组件。

如图即安装了桌面开发,又安装了wcf的组件就可以开始了。

管理员权限运行vs,首先新建一个wpf项目,这个大家应该都很熟悉。然后再在项目里添加新建项。

名称可以根据自己的业务命名。添加完成会在项目引用里多出一些dll文件。也会多出两个cs文件,那两个文件就是对外暴露的接口文件了,可以写一些业务逻辑给别人调用。

 

 ServiceModel就是比较主要的dll,我们用的一些服务都是这里面的。下面的ServiceModel.Web是我手动添加的。

同时项目里面的App.config配置文件会出现Wcf相关的配置。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="">
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <services>
            <service name="WpfWcf.Service1">
                <endpoint address="" binding="basicHttpBinding" contract="WpfWcf.IService1">
                    <identity>
                        <dns value="localhost" />
                    </identity>
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost:8733/Design_Time_Addresses/WpfWcf/Service1/" />
                    </baseAddresses>
                </host>
            </service>
        </services>
    </system.serviceModel>
</configuration>

 我是将system.serviceModel节点的相关东西都删掉了。然后换成了之前在网上找到的配置方法。大家可以直接拿来使用。主要是把 service name和conract相关的改成自己的项目的就行了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<system.serviceModel>
   <services>
     <service name="WpfTestWCF.Service1" behaviorConfiguration="default">
       <endpoint address="" behaviorConfiguration="webHttp" binding="webHttpBinding" bindingConfiguration="general" contract="WpfTestWCF.IService1">
         <identity>
           <dns value="localhost"/>
         </identity>
       </endpoint>
       <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
       <host>
         <baseAddresses>
           <add baseAddress="http://localhost:8733/Service1"/>
         </baseAddresses>
       </host>
     </service>
   </services>
   <behaviors>
     <endpointBehaviors>
       <behavior name="webHttp">
         <webHttp/>
       </behavior>
     </endpointBehaviors>
     <serviceBehaviors>
       <behavior name="default">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceThrottling maxConcurrentCalls="256" maxConcurrentSessions="1024" maxConcurrentInstances="1024"/>
         <serviceDebug includeExceptionDetailInFaults="true"/>
       </behavior>
     </serviceBehaviors>
   </behaviors>
   <bindings>
     <webHttpBinding>
       <binding name="general" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:01:00" sendTimeout="00:01:00" maxReceivedMessageSize="4194304" maxBufferSize="4194304" maxBufferPoolSize="33554432">
         <readerQuotas maxDepth="32" maxArrayLength="16384" maxStringContentLength="16384" maxBytesPerRead="8192" maxNameTableCharCount="65536"/>
         <security mode="None">
           <transport clientCredentialType="None"/>
         </security>
       </binding>
     </webHttpBinding>
   </bindings>
 </system.serviceModel>

 此时配置相关的算是已经配置好了。然后我们就需要启动服务和写接口了。我们在主窗口放一个button然后搞个点击事件。

事件里就写上启动服务的代码。

1
2
3
4
5
private void Button_Click(object sender, RoutedEventArgs e)
      {
          ServiceHost host = new ServiceHost(typeof(Service1));         
          host.Open();
      }

  记得关闭的时候释放下。

下面是接口相关。我们开始添加wcf服务的时候引入了两个主要的dll。

下面是我的接口名称定制部分。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
 
namespace WpfTestWCF
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
    [ServiceContract]
    public interface IService1
    {
        [OperationContract, WebGet(UriTemplate = "test?name={filename}", ResponseFormat = WebMessageFormat.Json)]
        string DoWork(string filename);
    }
}

  实现就是return filename,就是测试数据。

 

点击按钮启动服务。然后通过浏览器调用在app.config里定义好的服务地址,就可以调用到我们接口里的方法了,然后就可以像调用web服务一样了。

 

项目代码我就不上传了。已经讲的很详细了。我已经把代码整合到我的Surface Go项目里了,下面是GitHub的地址。

https://github.com/GreenShadeZhang/GreenShade.Net

 

1
<br><br>

 

posted @   绿荫阿广  阅读(1977)  评论(0编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示