接到有一个需求,需要web 端和我们的应用程序通讯,因为我们的客户端是C# 窗体程序,接到这个需求一下想到可以使用WCF 建立通讯,在过程中,涉及到跨域问题,研究了一番得以解决,当然还有其它的方式不如建立本地socket 服务一样,但我wcf 程序更加清晰,所以在此记录。
1. 建立工程
我这里使用VS2019 建立的窗体程序
2 .引入对应WCF 的Dll
右键引用 选择程序集
3. 边写wcf 接口定义
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp1.WCFService
{
/// <summary>
/// author : Mcally
/// @date : 2021年6月10日16:56:08
/// @des : 服务接口定制类
/// </summary>
[ServiceContract(Namespace = "http://www.mcally.net/")]
partial interface IWebPrintService
{
/// <summary>
/// 获取本地Ip示例
/// </summary>
/// <returns></returns>
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getIp", Method = "POST")]
GetIP GetLocalHostIps();
/// <summary>
/// 下载一个文件示例
/// </summary>
/// <returns></returns>
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json,
UriTemplate = "/dowload", Method = "GET")]
Stream DowloadFile();
}
}
4. 实现上面wcf 的接口定义
using System;
u