美文网首页
WCF简单例子+Asp.Net MVC调用+WinForm调用

WCF简单例子+Asp.Net MVC调用+WinForm调用

作者: 星辰相随 | 来源:发表于2019-02-27 14:08 被阅读0次

    1.创建WCF服务项目:

    阐述:WCF服务库与WCF服务应用程序的区别。

    WCF服务库,可以认为是一个包含WCF服务以及契约定义的类库。这儿库还不能直接运行,你可以在其他项目里引用,在宿主里启用托管这个库。

    而WCF应用程序,是一个可以执行的程序,它有独立的进程,WCF服务类契约的定义,可以直接看到运行的效果。此项目模板应该是基于IIS托管的程序。

    前者一般考虑WCF服务设计的时候,服务类的定义为单独的库,可以为其它项目使用。提高代码的复用性。

    后者在开发基于IIS托管的WCF服务程序时,比较多见,自学的时候也可以使用这种类型。

    当然你也可以修改这些代码,比如把WCF服务程序里的类,移到一个单独的类库里。

    1) WCF服务应用程序项目的创建:

    WCF服务应用程序的目录结构:

    IService1.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 WcfService

    {

        // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。

        [ServiceContract]

        public interface IService1

        {

            [OperationContract]

            /* 增加车票的方法*/

            void AddTicket(int count);

            [OperationContract]

            /*购买车票的方法*/

            int BuyTickets(int Num);

            [OperationContract]  //服务契约  即提供服务的实现方法

            /*查询车票的方法*/

            int GetRemainingNum();

            // TODO: 在此添加您的服务操作

        }

        // 使用下面示例中说明的数据约定将复合类型添加到服务操作。

        //数据契约 

        [DataContract] 

        public class Ticket

        {

            bool boolCount =true;//判断是否还有车票

            static int howmany = 10;//还有多少车票

            [DataMember]

            //判断是否还有票

            public bool BoolCalue

            {

                get { return boolCount; }

                set

                {

                    if (HowMany > 0)

                    {

                        boolCount = true;

                    }

                    else

                    {

                        boolCount = false;

                    }

                }

            }

            [DataMember]

            //返回票数

            public int HowMany

            {

                get { return howmany; }

                set { howmany = value; }

            }

        }

    }

    Service1.svc代码:

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Runtime.Serialization;

    using System.ServiceModel;

    using System.ServiceModel.Web;

    using System.Text;

    namespace WcfService

    {

        // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“Service1”。

        // 注意: 为了启动 WCF 测试客户端以测试此服务,请在解决方案资源管理器中选择 Service1.svc 或 Service1.svc.cs,然后开始调试。

        public class Service1 : IService1

        {

            Ticket T = null;

            public Service1() {

                T = new Ticket();

            }

            /*实现添加票数的方法*/

            public void AddTicket(int count)

            {

                T.HowMany = T.HowMany + count;

            }

            /*实现返回票数的方法*/

            public int GetRemainingNum()

            {

                return T.HowMany;

            }

            /*实现购买车票的方法*/

            public int BuyTickets(int Num)

            {

                if (T.BoolCalue)

                {

                    T.HowMany = T.HowMany - Num;

                    return 1;

                }

                else

                {

                    return 0;

                }

            }

        }

    }

    Web.config:

    <?xml version="1.0" encoding="utf-8"?>

    <configuration>

      <appSettings>

        <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />

      </appSettings>

      <system.web>

        <compilation debug="true" targetFramework="4.5" />

        <httpRuntime targetFramework="4.5"/>

      </system.web>

      <!--追加的代碼-->

      <system.serviceModel>

        <behaviors>

          <serviceBehaviors>

            <behavior>

              <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false -->

              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>

              <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->

              <serviceDebug includeExceptionDetailInFaults="false"/>

            </behavior>

          </serviceBehaviors>

        </behaviors>

        <protocolMapping>

            <add binding="basicHttpsBinding" scheme="https" />

        </protocolMapping>   

        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

      </system.serviceModel>

      <system.webServer>

        <modules runAllManagedModulesForAllRequests="true"/>

        <!--

            若要在调试过程中浏览 Web 应用程序根目录,请将下面的值设置为 True。

            在部署之前将该值设置为 False 可避免泄露 Web 应用程序文件夹信息。

          -->

        <directoryBrowse enabled="false"/>

      </system.webServer>

    </configuration>

    2) WCF服务库项目的创建:

    目录结构:

    IService1.cs与Service1.cs文件的源码同上。

    2.创建Asp.Net MVC 项目 调用WcfService:

    目录结构:

    1)添加服务引用:

    右键引用->添加服务引用->发现(找到自己刚刚创建的WCF应用程序服务:WcfService)->选中->确认

    再添加程序集 System.ServiceModel:

    右键引用->添加引用->System.ServiceModel

    TestController:

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.Web.Mvc;

    namespace WebApplication1.Controllers

    {

        public class TestController : Controller

        {

            // GET: Test

            public ActionResult Index()

            {

                ServiceReference1.Service1Client TClient = new WebApplication1.ServiceReference1.Service1Client();

                int i = TClient.BuyTickets(1); //调用WCF中的方法

                if (i == 1)

                {

                    //控制台输出

                    System.Diagnostics.Debug.WriteLine("------------购买成功--------------\n"+"当前票数:"+TClient.GetRemainingNum());

                }

                return View();

            }

        }

    }

    运行效果:

    3.创建WinForm窗体调用WcfService:

    项目名:WindowsFormsClient

    添加服务(程序集与WcfService):原理同上。

    目录结构:

    设计器的代码:

    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;

    namespace WindowsFormsClient

    {

        public partial class Form2 : Form

        {

            public Form2()

            {

                InitializeComponent();

            }

            ServiceReference1.Service1Client TClient = new WindowsFormsClient.ServiceReference1.Service1Client();

            //购买车票

            private void button1_Click(object sender, EventArgs e)

            {

                int i = TClient.BuyTickets(1); //调用WCF中的方法

                if (i == 1)

                {

                    this.label1.Text = "购买成功";

                }

                this.label1.Text += "剩余车票还有" + TClient.GetRemainingNum().ToString();

            }

            //查询票数

            private void button2_Click(object sender, EventArgs e)

            {

                this.label1.Text = "";

                this.label1.Text = TClient.GetRemainingNum().ToString();//调用WCF中的方法

            }

        }

    }

    源码下载地址:https://download.csdn.net/download/laizhixue/10969849

    ---------------------

    作者:laizhixue

    来源:CSDN

    原文:https://blog.csdn.net/laizhixue/article/details/87863873

    版权声明:本文为博主原创文章,转载请附上博文链接!

    相关文章

      网友评论

          本文标题:WCF简单例子+Asp.Net MVC调用+WinForm调用

          本文链接:https://www.haomeiwen.com/subject/ejxfuqtx.html