WCF Restful Service

對 Web Services、WCF 和 Restful 的掃盲可參見:https://www.cnblogs.com/scy251147/p/3382436.htmlhtml

關於以前對 WCF 的學習,可參見:WCF | wjcx_sqhweb

首先,對 Restful Service 做簡單的瞭解架構

  • 建立分佈式超文本媒體的一種架構方式
  • 獨立於任何技術、平臺,面向資源 Resource-Oriented Architecture (ROA)
  • 經過標準的HTTP(GET,POST,PUT,DELETE)操做來定義資源
  • 經過 Uniform Resource Identifier(URI)發佈資源

首先,定義服務,簡單之app

[ServiceContract(Name = "user")]
public interface IServiceWCF
{
	[OperationContract]
	[WebInvoke(Method = "GET", 
		UriTemplate = "getUser/{name}", 
		RequestFormat = WebMessageFormat.Json, 
		ResponseFormat = WebMessageFormat.Json)]
	UserData GetUserData(string name);
}

[AspNetCompatibilityRequirements(
	RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ServiceWCF : IServiceWCF
{
	public UserData GetUserData(string name) {
	  //服務接口方法實現
	}
}

其中,AspNetCompatibilityRequirements 指示該服務可否在 ASP.NET 兼容模式下運行,也能夠加上分佈式

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 

用於指示說明服務端只會存在這類的一個實例。服務定義完成後,須要更新配置文件 Web.Configpost

<system.serviceModel>
  <services>
    <service name="RestfulWcf.ServiceWCF" behaviorConfiguration="defaultServiceBehavior">
      <endpoint address="" binding="webHttpBinding" contract="RestfulWcf.IServiceWCF"
                behaviorConfiguration="defaultEndpointBehavior"></endpoint>
    </service>
  </services>
    
  <behaviors>
    <serviceBehaviors>
      <behavior name="defaultServiceBehavior">
        <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
      <behavior name="defaultServiceBehaviorHttps">
        <!-- 爲避免泄漏元數據信息,請在部署前將如下值設置爲 false -->
        <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
        <!-- 要接收故障異常詳細信息以進行調試,請將如下值設置爲 true。在部署前設置爲 false 以免泄漏異常信息 -->
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
      
    <endpointBehaviors>
      <behavior name="defaultEndpointBehavior">
        <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true" />
        <dataContractSerializer maxItemsInObjectGraph="6553500"/>
      </behavior>
    </endpointBehaviors>
  </behaviors>
    
  <protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
  </protocolMapping>
    
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />    
</system.serviceModel>

同時,新增 Global.asax 全局資源文件,用於定義註冊路由學習

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        RegistrRoutes();
    }

    private void RegistrRoutes()
    {
        //ServiceRoute須要顯式引用 System.ServiceModel.Activation.dll
        RouteTable.Routes.Add(
            new ServiceRoute("user", new WebServiceHostFactory(), typeof(ServiceWCF)));
    }
}

最後,可 Service.svc直接右鍵運行,也可部署至 IIS網站

項目-屬性,生成路徑應爲bin目錄,IIS部署時,網站路徑指向該路徑便可

經過該路徑能夠查看該服務接口發佈的方法ui

http://localhost:18800/user/help

若在調用PUT或DELETE方法時出現 Status:405 Method Not Allowed 問題,在 web.config中 system.webServer節點添加以下配置 url

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

詳細配置過程,參見(推薦): WCF RESTFul 服務搭建

參考

關於如何配置 https 的訪問參見:http://www.cnblogs.com/mingmingruyuedlut/p/4236035.html

須要分別在 serviceModel和 services中添加 https配置

<bindings>
  <webHttpBinding >
    <binding name="SecureWebBinding" >
      <security mode="Transport">
        <transport clientCredentialType="None"></transport>
      </security>
    </binding>
  </webHttpBinding>
</bindings>

<endpoint address="" binding="webHttpBinding"
          bindingConfiguration="SecureWebBinding"
          contract="RestfulWcf.IServiceWCF"
          behaviorConfiguration="defaultEndpointBehavior"/>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>

不要忘記在 IIS中爲該服務綁定 443端口便可。

Restful WCF Service 已是過期的技術,推薦進一步學習 WebApi,具體參見:C# - MVC WebApi | wjcx_sqh

相關文章
相關標籤/搜索