c# 編寫REST的WCF

  REST(Representational State Transfer)即 表述性狀態傳遞 ,簡稱REST,通俗來說就是:資源在網絡中以某種表現形式進行狀態轉移。web

  RESTful是一種軟件架構風格、設計風格,而不是標準,只是提供了一組設計原則和約束條件。ajax

  在三種主流的Web服務實現方案中,由於REST模式的Web服務與複雜的SOAP和XML-RPC對比來說明顯的更加簡潔,愈來愈多的web服務開始採用REST風格設計和實現。json

  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文件app

  

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文件中添加配置。post

 

<?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/asui

                     Post:url

$.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我只是學習而已。

相關文章
相關標籤/搜索