WCF基础

       在上篇博客中,我们讲到了如何理解  面向过程,面向对象,面向服务,怎样理解WCF,接下来,我们就看一下,我们如何用WCF


1、新建解决方案,选择项目类型为WCF服务应用程序

  

   

       然后就会出现你已经新建了的项目,我们删掉默认的Service.svc和IService.cs,自己新建,添加Wcf服务,至于对应的接口,他自己就自动添加上了,就不用自己操心了

                



2、然后我们在ITest中写接口方法:PrintWord(str)

namespace WcfService1
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“ITest”。
    [ServiceContract]
    public interface ITest
    {
        [OperationContract]
        void DoWork();

        [OperationContract]
        string PrintWord(String str);
    }
}


3、接着,在Test中写实现ITest的方法:

namespace WcfService1
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“Test”。
    // 注意: 为了启动 WCF 测试客户端以测试此服务,请在解决方案资源管理器中选择 Test.svc 或 Test.svc.cs,然后开始调试。
    public class Test : ITest
    {
        public void DoWork()
        {
        }
        public string PrintWord(string str) 
        {
            string word = "作者是:";
            word = word + str;
            return word;
        }
    }
}

大家一定注意到了,这个ITest里面的接口都有特殊的地方,这是因为wcf中的接口添加了两个上下文

[ServiceContract] 有这个说明本接口是一个WCF的接口

[OperationContract] 有这个说明本接口方法是一个WCF的方法

如果没有呢,我们可以试试,是不能被外界调用的。


4、然后,我们进行一下测试:直接F5运行:


这就证明成功了!



然后,我们作为客户调用的时候是如何用的呢?


我们需要的东西就有这一样!

然后我们看客户端:

<?xml version="1.0" encoding="utf-8"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="1.0.0.0" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </profile>
    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <roleManager defaultProvider="DefaultRoleProvider">
      <providers>
        <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </roleManager>
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="ICSharpCode.SharpZipLib" publicKeyToken="1b03e6acf1164f73" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-0.84.0.0" newVersion="0.84.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>


  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="FreshStudentResport">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <bindings>
      <wsHttpBinding>
        <binding name="WsHttpBinding_Default" transactionFlow="true" closeTimeout="00:10:00" receiveTimeout="00:20:00" sendTimeout="00:20:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" useDefaultWebProxy="false">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>

    <services>
      <service name="ITOO.FreshReport.WCFService.FreshStudentReportService" behaviorConfiguration="FreshStudentResport">
      </service>
    </services>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="1" />
    <!--**********************begin—具体的一个节点配置*******************************-->
    <client>
      <!--本系统的配置-->     
      <pre name="code" class="html">       <endpoint address="http://localhost:6326/Service.svc?wsdls" binding="wsHttpBinding" bindingConfiguration="WsHttpBinding_Default" contract="ITOO.FreshReport.Contracts.IFreshStudentReportService" name="WsHttpBinding_Services" /><span style="font-family: Arial, Helvetica, sans-serif;">      </span>
</client> <!--********************end—具体的一个节点配置****************************--> </system.serviceModel> </configuration>




其中我们有一项配置终结点:

<endpoint address="http://localhost:6326/Service.svc?wsdls" binding="wsHttpBinding" bindingConfiguration="WsHttpBinding_Default" contract="ITOO.FreshReport.Contracts.IFreshStudentReportService" name="WsHttpBinding_Services" />      
       这里面包括一个abc之说,adress地址,bindding绑定,contract契约。其中,地址定义了服务的位置,绑定定义了服务通信的方式,契约定义了服务的内容。WCF中便用终结点表示这样一种组成关系,终结点就是地址、契约与绑定的混成品。

当然仅仅有这个还是不够的,我们还要引用已发布的nuget包(或者是已经打好的dll),然后,我们就成了!



总结:

       这还是第一次这么专注一个东西,发现其实挺好的,学到的东西比用过之后还要有收获!


posted @ 2016-02-21 17:10  Double-Eggs  阅读(206)  评论(0编辑  收藏  举报