C#.NET Winform承载WCF RESTful API (硬编码配置)

1.新建一个名为“WindowsForms承载WCF”的WINFORM程序。

2.在解决方案里添加一个“WCF 服务库”的项目,名为“WcfYeah”。

3.修改IService1文件,内容如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfYeah
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
    [ServiceContract]
    public interface IService1
    {        
        [OperationContract]
        [WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        CompositeType geta(CompositeType composite);
    }

    // 使用下面示例中说明的数据约定将复合类型添加到服务操作。
    // 可以将 XSD 文件添加到项目中。在生成项目后,可以通过命名空间“WcfYeah.ContractType”直接使用其中定义的数据类型。
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}

4.修改Service1,内容如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfYeah
{
    // 调整 ServiceBehavior,使其支持并发
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerCall, UseSynchronizationContext = false)]
    public class Service1 : IService1
    {
        public CompositeType geta(CompositeType composite)
        {
            CompositeType myret = new CompositeType();
            try
            {
                if(composite==null)
                    myret.StringValue = "输入实体为空:" + DateTime.Now.ToString();
                else
                    myret.StringValue = "输入实体不为空:" + DateTime.Now.ToString();
            }
            catch (Exception ex)
            {
                myret.StringValue = "发生异常:" + ex.Message;                 
            }
            return myret;
        }

    }
}

5.在WCF项目中增加一个WCFServer类,内容如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;

namespace WcfYeah
{
    public class WCFServer
    {
        public WebServiceHost host = null;

        public WCFServer()
        {
            /* 硬编码形式配置WCF服务
             * WebServiceHost需要在项目中右键引用System.ServiceModel.Web.dll程序集
             *  */

            //对外连接数,根据实际情况加大
            if (ServicePointManager.DefaultConnectionLimit < 100)
                System.Net.ServicePointManager.DefaultConnectionLimit = 100;            

            string port = "16110";

            Uri baseURI = new Uri("http://localhost:" + port.ToString() + "/myapi");
            //注意:这里是实现类,不是接口,否则会报:ServiceHost 仅支持类服务类型。
            host = new WebServiceHost(typeof(Service1), baseURI);

            WebHttpBinding binding = new WebHttpBinding();
            // 这里不需要安全验证
            binding.Security.Mode = WebHttpSecurityMode.None;
            host.AddServiceEndpoint(typeof(IService1), binding, "");
            binding.MaxReceivedMessageSize = 2147483647;
            binding.MaxBufferSize = 2147483647;
            binding.MaxBufferPoolSize = 2147483647;

            binding.OpenTimeout = new TimeSpan(0, 10, 0);
            binding.CloseTimeout = new TimeSpan(0, 10, 0);
            binding.SendTimeout = new TimeSpan(0, 10, 0);
            binding.ReceiveTimeout = new TimeSpan(0, 10, 0);

            //项目需要引用System.Runtime.Serialization.dll
            binding.ReaderQuotas.MaxDepth = 2147483647;
            binding.ReaderQuotas.MaxStringContentLength = 2147483647;
            binding.ReaderQuotas.MaxArrayLength = 2147483647;
            binding.ReaderQuotas.MaxBytesPerRead = 2147483647;
            binding.ReaderQuotas.MaxNameTableCharCount = 2147483647;

            ServiceThrottlingBehavior mdBehavior = new ServiceThrottlingBehavior()
            {
                MaxConcurrentCalls = 160,
                MaxConcurrentInstances = 260,
                MaxConcurrentSessions = 100
            };
            host.Description.Behaviors.Add(mdBehavior);
        }


        public void Start()
        {
            host.Open();
        }

        public void Close()
        {
            if (host != null)
            {
                host.Close();
            }
        }

    }
}

6.回到WINFORM程序,在FORM LOAD中启动这个WCF,FormClosing中关闭这个WCF。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WcfYeah;

namespace WindowsForms承载WCF
{
    public partial class Form1 : Form
    {
        WCFServer wcfs = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                wcfs = new WCFServer();
                wcfs.Start();
                lblTip.Text = "服务已运行";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (wcfs != null)
                {
                    wcfs.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

7.用管理员权限启动这个WINFORM程序。

8.使用POSTMAN调用。

地址:http://localhost:16110/myapi/geta

请求报文:

{
    "BoolValue": true,
    "StringValue": "11"
}
响应报文:
{
    "BoolValue": true,
    "StringValue": "输入实体不为空:2021/11/30 9:38:41"
}
 
 
原文地址:https://www.cnblogs.com/runliuv/p/15622841.html