1):用VS2013创建一个WCF的工程,如下图所示:

2):我们来看一下默认状态下的config文件内容,这里的内容我们会再后续的步骤中进行修改

<?xml version="1.0"?>
<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>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <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"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

3):我们对工程文件及其内容做一下修改,具体代码如下所示:

3.1):UserData class

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

namespace EricSunWcfService
{
    [DataContract]
    public class UserData
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Password { get; set; }
        [DataMember]
        public string Email { get; set; }
    }
}

3.2):IDataService,这个接口是从默认的IService1修改而来,并且这里提供了两种方法,一个是GET,另外是POST,都是简单的返回UserData对象的Json字符串

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

namespace EricSunWcfService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IUserService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "getuser/{name}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        UserData GetUserData(string name);

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "checkuser", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        UserData CheckUserData(UserData user);
    }
}

3.3):UserService,这个文件名是从默认的Service1修改过来的

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

namespace EricSunWcfService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class UserService : IUserService
    {
        public UserData GetUserData(string name)
        {
            UserData user = new UserData();
            user.Name = name;
            user.Email = "test@123.com";
            return user;
        }

        public UserData CheckUserData(UserData user)
        {
            user.Name += "-test";
            return user;
        }
    }
}

3.4):我们可以点击对应的Service的‘View Markup’来修改ServiceHost的信息,如下图所示

4):我们在IIS中创建一个Site来Host我们所提供的WCF Service,用http协议并且将端口绑定为8089,与此同时制定好Physical path,如下图所示

【注:请将创建的Application Pool的.Net Framework Version修改成为4.0】

5):在目前这种状态下还不能成功的访问对应的WCF Service的,我们需要对web.config进行修改

<?xml version="1.0"?>
<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>
    <services>
        <service name="EricSunWcfService.UserService" behaviorConfiguration="RESTBehaviour">
          <endpoint address=""
                    binding="webHttpBinding"
                    contract="EricSunWcfService.IUserService"
                    behaviorConfiguration="ESEndPointBehavior"/>
        </service>
      </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="RESTBehaviour">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>

        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ESEndPointBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <!--
      To browse web app root directory during debugging, set the value below to true.
      Set to false before deployment to avoid disclosing web app folder information.
    -->
    <directoryBrowse enabled="true"/>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

6):config文件配置完毕后,我们就可访问此URL:http://localhost:8089/UserService.svc 来判断我们Service提供的正确与否,若是看到下面的截图则表明Service无误

7):若在访问 http://localhost:8089/UserService.svc 的时候出现500.19【HTTP Error 500.19 - Internal Server Error】错误请参考如下链接解决

http://www.cnblogs.com/mingmingruyuedlut/archive/2011/11/04/2235630.html

8):访问GET方法我们可以直接在浏览器地址栏中输入对应的service地址即可访问

例如输入 http://localhost:8089/UserService.svc/getuser/eric

会给我们返回: {"Email":"test@123.com","Name":"eric","Password":null}

9):若是访问POST方法,单纯的在浏览器中输入地址则无法完成正确的调用,这里我们使用浏览器的插件poster (https://addons.mozilla.org/en-US/firefox/addon/poster/)

如上图所示,在poster中填入正确的配置信息,并且传入Json的参数值{"Email":"test@123.com","Name":"eric","Password":"123"}

点击POST按钮之后变回得到如下返回结果:

10):若是我们发现在调用PUT或者DELETE方法时出现Status:405 Method Not Allowed的问题,请在web.config文件中的system.webServer节点中添加如下配置

    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
    </modules>
    <handlers>
      <remove name="WebDAV" />
    </handlers>

至此我们就可以通过WCF向外提供REST的Service了~~

如何配置来完成HTTPS的访问请看如下链接:

http://www.cnblogs.com/mingmingruyuedlut/p/4236035.html

利用WCF创建简单的RESTFul Service的更多相关文章

  1. SpringBoot IntelliJ创建简单的Restful接口

    使用SpringBoot快速建服务,和NodeJS使用express几乎一模一样,主要分为以下: 1.添加和安装依赖  2.添加路由(即接口) 3.对路由事件进行处理 同样坑的地方就是,祖国的防火墙太 ...

  2. 利用HttpListener创建简单的HTTP服务

    using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using ...

  3. 基于.Net FrameWork的 RestFul Service

    关于本文 这篇文章的目的就是向大家阐述如何在.net framework 4.0中创建RestFul Service并且使用它. 什么是web Services,什么是WCF 首先讲到的是web Se ...

  4. 用 C# 实现一个简单的 Rest Service 供外部调用

    用 C#  实现一个简单的 Restful Service 供外部调用,大体总结为4点: The service contract (the methods it offers). How do yo ...

  5. Wcf Restful Service服务搭建

    目的 使用Wcf(C#)搭建一个Restful Service 背景 最近接到一个项目,客户要求使用Restful 方式接收到数据,并对数据提供对数据的统计显示功能,简单是简单,但必须要使用Restf ...

  6. WCF Restful Service的服务

    构建基于WCF Restful Service的服务 前言 传统的Asmx服务,由于遵循SOAP协议,所以返回内容以xml方式组织.并且客户端需要添加服务端引用才能使用(虽然看到网络上已经提供了这方面 ...

  7. 构建基于WCF Restful Service的服务

    前言 传统的Asmx服务,由于遵循SOAP协议,所以返回内容以xml方式组织.并且客户端需要添加服务端引用才能使用(虽然看到网络上已经提供了这方面的Dynamic Proxy,但是没有这种方式简便), ...

  8. Web Service 的创建简单编码、发布和部署

    最近,老大准备将已有的C/S架构项目中的通信部分做成通用,需要将其支持WebService为以后项目向着B/S架构升级做好铺垫,为此身为屌丝的我去各种百度WebService是个什么卵玩意,然后逐渐搭 ...

  9. 使用WCF 创建 Rest service

    REST SERVICE 允许客户端修改url路径,并且web端功过url 请求数据. 他使用http协议进行通讯,想必大家都知道 . 并且我们可以通过设置进行数据类型转换, 支持XML,JSON 格 ...

随机推荐

  1. ASP.NET MVC的TextBoxFor()和TextBox()

    先来看看2者的语法:TextBoxFor():MvcHtmlString Html.TextBoxFor(Expression<Func<TModel,TValue>> exp ...

  2. java &quot;&quot;.split(&quot;,&quot;)

    String[] string = "".split(","); 结果是string = []; String[] string = " " ...

  3. mac jdk环境变量

    /System/Library/Java/JavaVirtualMachines/1.6.0.jdk /Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk ...

  4. codeforces C. Triangle

    C. Triangle time limit per test 1 second memory limit per test 256 megabytes input standard input ou ...

  5. ios学习笔记

    1.对于autorelease的理解 Each thread in a Cocoa application maintains its own stack of autorelease pool bl ...

  6. 5.Primitive, Reference, and Value Types

    1.Programming Language Primitive Types primitive types:Any data types the compiler directly supports ...

  7. [转]Struts标签库详解

    本文转自:http://hi.baidu.com/xzkcz/blog/item/5cf9f91f01beb9f4e0fe0bd4.html   Struts提供了五个标签库,即:HTML.Bean. ...

  8. 骑士周游问题 --- 递归解法 --- java代码

    骑士游历: 定义了向量的数组M,行数组X,列数组Y, 棋盘plane,计数器count,走动步数step 需要注意的是,递归函数的进入前的验证,原先的想法是传入来时的方向参数,可是这样的想法被实践否定 ...

  9. Django 1.6 最佳实践: 如何正确使用 Signal(转)

    原文:http://www.weiguda.com/blog/38/ 如何正确的使用signal: 简单回答是: 在其他方法无法使用的情况下, 才最后考虑使用signal. 因为新的django开发人 ...

  10. POJ 3207 Ikki&#39;s Story IV - Panda&#39;s Trick (2-SAT,基础)

    题意: 有一个环,环上n个点,现在在m个点对之间连一条线,线可以往圆外面绕,也可以往里面绕,问是否必定会相交? 思路: 根据所给的m条边可知,假设给的是a-b,那么a-b要么得绕环外,要么只能在环内, ...