WCF应用 - 简单的Rest服务

简介: 1. 什么是REST?  Rest的全称是Representational State Transfer, 普通的WCF使用SOAP,而使用REST构建的WCF服务使用其他数据传输方式,例如JSONRest的四种操作:GET - Requests a specific re...

1. 什么是REST?

  Rest的全称是Representational State Transfer, 普通的WCF使用SOAP,而使用REST构建的WCF服务

使用其他数据传输方式,例如JSON

Rest的四种操作:

  1. GET - Requests a specific representation of a resource
  2. PUT - Creates or updates a resource with the supplied representation
  3. DELETE - Deletes the specified resource
  4. POST - Submits data to be processed by the identified resource

 

 

2. 什么情况下使用REST?

  1. Less overhead (no SOAP envelope to wrap every call in)
  2. Less duplication (HTTP already represents operations like DELETE, PUT, GET, etc. that have to otherwise be represented in a SOAP envelope).
  3. More standardized - HTTP operations are well understood and operate consistently. Some SOAP implementations can get finicky.
  4. More human readable and testable (harder to test SOAP with just a browser).
  5. Don't need to use XML (well, you kind of don't have to for SOAP either but it hardly makes sense since you're already doing parsing of the envelope).
  6. Libraries have made SOAP (kind of) easy. But you are abstracting away a lot of redundancy underneath as I have noted. Yes, in theory, SOAP can go over other transports so as to avoid riding atop a layer doing similar things, but in reality just about all SOAP work you'll ever do is over HTTP.

3. 简单的例子

  1) 首先,制作服务契约的接口

  IHelloService

using System.ServiceModel;
using System.ServiceModel.Web;

namespace Perseus.WCF.REST.Contract.Service
{
    [ServiceContract]
     public  interface IHelloService
    {
        [OperationContract]
        [WebInvoke(Method =  " GET ",
            ResponseFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate =  " xml/{name}/{age} ")]
         string HelloXml( string name,  string age);

        [OperationContract]
        [WebInvoke(Method =  " GET ",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate =  " json/{name}/{age} ")]
         string HelloJson( string name,  string age);
    }
}

 

  2) 然后, 新建一个WCF服务项目,在项目中添加WCF服务文件svc

HelloService.svc

using Perseus.WCF.REST.Contract.Service;

namespace Perseus.WCF.REST.Service
{
     public  class HelloService : IHelloService
    {
         public  string HelloXml( string name,  string age)
        {
             return  " Hello  " + name +  "   "
                   +  " Your Age:  " + age;
        }

         public  string HelloJson( string name,  string age)
        {
             return  " Hello  " + name +  "   "
                   +  " Your Age:  " + age;
        }
    }
}

 

  3) 配置文件

<? xml version="1.0" ?>
< configuration >
   < connectionStrings >
     < add  name ="NorthwindConnectionString"  connectionString ="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True"  providerName ="System.Data.SqlClient" />
   </ connectionStrings >
   < system.web >
     < compilation  debug ="true"  targetFramework ="4.0"   />
   </ system.web >
   < system.serviceModel >
     < services >
       < service  name ="Perseus.WCF.REST.Service.HelloService"  behaviorConfiguration ="ServiceBehaviour" >
         <!--  Service Endpoints  -->
         <!--  Unless fully qualified, address is relative to base address supplied above  -->
         < endpoint  address =""   binding ="webHttpBinding"  contract ="Perseus.WCF.REST.Contract.Service.IHelloService"  behaviorConfiguration ="web" >
           <!--  
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          
-->
         </ endpoint >
       </ service >
       </ services >

     < behaviors >
       < endpointBehaviors >
         < behavior  name ="web" >
           < webHttp  />
         </ behavior >
       </ endpointBehaviors >
       < serviceBehaviors >
         < behavior  name ="ServiceBehaviour" >
           < serviceMetadata  httpGetEnabled ="true"   />
           < serviceDebug  includeExceptionDetailInFaults ="false"   />
         </ behavior >
         < behavior  name ="" >
           < serviceMetadata  httpGetEnabled ="true"   />
           < serviceDebug  includeExceptionDetailInFaults ="false"   />
         </ behavior >
       </ serviceBehaviors >
     </ behaviors >
     < serviceHostingEnvironment  multipleSiteBindingsEnabled ="true"   />
   </ system.serviceModel >
   < system.webServer >
     < modules  runAllManagedModulesForAllRequests ="true" />
   </ system.webServer >

</ configuration >

 

   4) 地址栏调试

http://localhost:7695/HelloService.svc/xml/david/30

返回结果:

  < HelloXmlResponse  xmlns ="http://tempuri.org/" >
   < HelloXmlResult >Hello david Your Age: 30 </ HelloXmlResult > 
   </ HelloXmlResponse >

 

http://localhost:7695/HelloService.svc/json/david/30

返回结果:

{"HelloJsonResult":"Hello david Your Age: 30"}

 

   5) 编写客户端调用代码

HelloRestTest

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using Perseus.WCF.REST.Contract.Service;

namespace Perseus.WCF.Client
{
     class HelloRestTest : ITestCase
    {
         public  void Run()
        {
            Console.Write( " Please Input Your Name:  ");
             string name = Console.ReadLine();
            Console.Write( " Please Input Your Age:  ");
             string age = Console.ReadLine();

             string url =  " http://localhost:7695/HelloService.svc ";

             using (WebChannelFactory<IHelloService> wcf 
                =  new WebChannelFactory<IHelloService>( new Uri(url)))
            {
                 var channel = wcf.CreateChannel();
                IClientChannel clientchanel = channel  as IClientChannel;
                 string result = channel.HelloJson(name, age);
                Console.WriteLine(result);
            }


        }
    }
}

 

  运行结果:

Hello david Your Age: 30

 

 

 

目录
相关文章
|
10月前
|
前端开发
WCF更新服务引用报错的原因之一
WCF更新服务引用报错的原因之一
|
9月前
|
C# 数据安全/隐私保护
c#如何创建WCF服务到发布(SqlServer版已经验证)
c#如何创建WCF服务到发布(SqlServer版已经验证)
38 0
|
9月前
|
安全 数据库连接 数据库
WCF服务创建到发布(SqlServer版)
在本示例开始之前,让我们先来了解一下什么是wcf? wcf有哪些特点? wcf是一个面向服务编程的综合分层架构。该架构的项层为服务模型层。 使用户用最少的时间和精力建立自己的软件产品和外界通信的模型。它使得开发者能够建立一个跨平台的安全、可信赖、事务性的解决方案。且能与已有系统兼容写作。 简单概括就是:一组数据通信的应用程序开发接口。
62 0
|
10月前
Visual Studio 2022 创建 WCF服务 找不到
Visual Studio 2022 创建 WCF服务 找不到
|
C++
WCF基础教程(二)——解析iis8和iis8.5+VS2013发布wcf服务问题
WCF基础教程(二)——解析iis8和iis8.5+VS2013发布wcf服务问题
102 0
WCF基础教程(二)——解析iis8和iis8.5+VS2013发布wcf服务问题
WCF使用纯代码的方式进行服务寄宿
服务寄宿的目的是为了开启一个进程,为WCF服务提供一个运行的环境。通过为服务添加一个或者多个终结点,使之暴露给潜在的服务消费,服务消费者通过匹配的终结点对该服务进行调用,除去上面的两种寄宿方式,还可以以纯代码的方式实现服务的寄宿工作。
850 0
|
Windows
WCF服务寄宿到IIS
一.WCF简介: Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台。整合了原有的windows通讯的 .net Remoting,WebService,Socket的机制,并融合有HTTP和FTP的相关技术。
1048 0
WCF服务自我寄宿
WCF服务的寄宿方式 WCF寄宿方式是一种非常灵活的操作,可以寄宿在各种进程之中,常见的寄宿有: IIS服务、Windows服务、Winform程序、控制台程序中进行寄宿,从而实现WCF服务的运行,为调用者方便、高效提供服务调用。
996 0
|
网络架构
(纯代码)快速创建wcf rest 服务
因为有一个小工具需要和其它的业务对接数据,所以就试一下看能不能弄一个无需配置快速对接的方法出来,百(以)度(讹)过(传)后(讹),最后还是对照wcf配置对象调试出来了: 1.创建WebHttpBinding 2.
979 0