zoukankan      html  css  js  c++  java
  • WCF Restful Service

    对 Web Services、WCF 和 Restful 的扫盲可参见:https://www.cnblogs.com/scy251147/p/3382436.html

    关于之前对 WCF 的学习,可参见:WCF | wjcx_sqh

    首先,对 Restful Service 作简单的了解

    • 创建分布式超文本媒体的一种架构方式
    • 独立于任何技术、平台,面向资源 Resource-Oriented Architecture (ROA)
    • 通过标准的HTTP(GET,POST,PUT,DELETE)操作来定义资源
    • 通过 Uniform Resource Identifier(URI)发布资源

    首先,定义服务,简单之

    [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.Config

    <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部署时,网站路径指向该路径即可
    

    通过该路径可以查看该服务接口发布的方法

    http://localhost:18800/user/help
    

    若在调用PUT或DELETE方法时出现 Status:405 Method Not Allowed 问题,在 web.config中 system.webServer节点添加如下配置 

    <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

  • 相关阅读:
    Android Context 上下文 你必须知道的一切
    Delphi:对TNotifyEvent的理解
    vagrant启动报错The following SSH command responded with a no
    virtualbox命令行共享CentOS目录
    一些Linux命令
    PHP实现单例模式
    maven+springMVC+mybatis+easyUI管理用户增删改查
    Project Euler:Problem 77 Prime summations
    spring 获取对象方式
    linux命令之man和info
  • 原文地址:https://www.cnblogs.com/wjcx-sqh/p/11093973.html
Copyright © 2011-2022 走看看