首页 > 技术文章 > c# 编写REST的WCF

TBW-Superhero 2018-03-21 19:04 原文

  REST(Representational State Transfer)即 表述性状态传递 ,简称REST,通俗来讲就是:资源在网络中以某种表现形式进行状态转移。

  RESTful是一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。

  在三种主流的Web服务实现方案中,因为REST模式的Web服务与复杂的SOAP和XML-RPC对比来讲明显的更加简洁,越来越多的web服务开始采用REST风格设计和实现。

  1.首先建立解决方案创建WCF项目,删除默认生成文件,创建Interface和Services文件夹。

  2.创建ITestService.cs文件;

    

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

namespace WCFSERVICE.Interface
{

    [ServiceContract]
    public  interface ITestService
    {
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "Test1", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
        string Test1(string userName, string password);
       
        [OperationContract]
        [WebGet(UriTemplate = "Test/{id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
       
        string Test(string id);        

        
    }
}

3.创建TestService.cs文件

  

namespace WCFSERVICE.Services
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class TestService : ITestService
    {
        
        public string Test1(string userName, string password)
        {
            if (!Validate.IsValidate(userName, password))
            {

            }
            
            return "";
        }

        
        public string Test(string id)
        {
            
            return id;
        }      


    }
}

4.在Web.config文件中添加配置。

 

<?xml version="1.0" encoding="utf-8"?>
<configuration> 
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
    <appSettings>
    <add key="SqlConnectString" value="data source=192.168.1.2;initial catalog=TEST;user id=sa;password=123456;"/>    
  </appSettings>
  <system.serviceModel>
     
      <service name="LWCFSERVICE.Services.TestService"    >
        <endpoint address="" behaviorConfiguration="webbehavioree"
          binding="webHttpBinding" contract="WCFSERVICE.Interface.ITestService" />

      </service>

    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webbehavior">
          <webHttp />
        </behavior>       

      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" >
      <serviceActivations>
        <add relativeAddress="./Service/TestService.svc" service="WCFSERVICE.Service.TestService"/>        
      </serviceActivations>

    </serviceHostingEnvironment>


  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        若要在调试过程中浏览 Web 应用程序根目录,请将下面的值设置为 True。
        在部署之前将该值设置为 False 可避免泄露 Web 应用程序文件夹信息。
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>
   
  
</configuration>

5.在Global.asax的Application_Start方法中添加路由规则。

using WCFSERVICE.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace WCFSERVICE
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();
            System.Web.Routing.RouteTable.Routes.Add(new System.ServiceModel.Activation.ServiceRoute("TestService", new System.ServiceModel.Activation.WebServiceHostFactory(), typeof(TestService)));      

             


        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}

6.访问方式:Get:  http://localhost:63980/TestService/Test/as

                     Post:

$.ajax({
            type: "post",
            url: "http://localhost:61756/TestService/Test1",
            contentType: "application/json",
            dataType: "application/json",
            data: { username: "test", password: "test" },
            success: function (data, status) {
                console.log(data);
                console.log(status);
            }
        });

 注:项目实战编写WEBAPI方式更好,RESTful的WCF我只是学习而已。

推荐阅读