WCF搭建Web接口

    xiaoxiao2022-07-13  153

    本文仅为个人理解,如有错误请指正。

    WCF基本概念:

    Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台。整合了原有的windows通讯的 .net Remoting,WebService,Socket的机制,并融合有HTTP和FTP的相关技术。

    Demo代码:

    private void button9_Click(object sender, EventArgs e) { if (WCFHost == null) { //创建宿主,设置基地址 WCFHost = new ServiceHost(typeof(WCFService), new Uri("http://127.0.0.1/WCFService")); //创建终结点,绑定为WebHttpBinding,设置路径 ServiceEndpoint sendPoint = WCFHost.AddServiceEndpoint(typeof(ISendInfo), new WebHttpBinding(), "Send"); //添加终结点行为,使之能够支持Web服务 sendPoint.EndpointBehaviors.Add(new WebHttpBehavior()); ServiceEndpoint changePoint = WCFHost.AddServiceEndpoint(typeof(IChangeInfo), new WebHttpBinding(), "Change"); changePoint.EndpointBehaviors.Add(new WebHttpBehavior()); //打开服务 WCFHost.Open(); } } [ServiceContract] public interface ISendInfo { [WebGet(UriTemplate= "SendInfo", ResponseFormat = WebMessageFormat.Json)] string SendInfo(); } [ServiceContract] public interface IChangeInfo { [WebInvoke(Method ="GET",UriTemplate ="ChangeInfo/{value}",ResponseFormat = WebMessageFormat.Xml)] string ChangeInfo(string value); } [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class WCFService : ISendInfo,IChangeInfo { public string ChangeInfo(string value) { return "ChangeInfo:" + value; } public string SendInfo() { return "SendInfo:" + (new Random()).Next(0, 100); } }

    访问路径:

       访问地址:基地址/终结点地址/UriTemplate

    SendInfo:127.0.0.1/WCFService/Send/SendInfoChangeInfo:127.0.0.1/WCFService/Change/ChangeInfo/123

    WebGet和WebInvoke说明

    WebGet和WebInvoke都是把当前服务暴露出去,允许浏览器直接调用此服务。WebGet和WebInvoke都实现了IOperationContractAttributeProvider接口,所以无需再对操作单独添加[OperationContract]。程序集:System.ServiceModel.Web.dllWebGet必须设置UriTemplate,WebInvoke必须设置UriTemplate和MethodRequestFormat属性:请求格式,支持Xml和JsonResponseFormat属性:响应格式,支持Xml和JsonMethod属性:WebInvoke独有,服务操作响应的协议,只可以填写GET/PUT/POST/DELETE,只允许为大写格式UriTemplate:服务的统一资源标识符模板,通过该属性实现对URL带参数访问,UriTemplate使用'{}'对参数占位‘{}’中为对应的参数名,如:/GetString/{xxx}、/GetString/xxx={xxx}、/{xxx}、/Getstring_{xxx}

    WebGet和WebInvoke区别

    WebInvoke更适用于对数据进行操作(增删改)WebGet的定义提交方式类似'GET'更适用于查询数据(数据呈现)

    AspNetCompatibilityRequirementsAttribute说明

    程序集:System.ServiceModel.dll,只允许标记在类上。用于是否可以在ASP.NET兼容性代码中运行该服务,一般建议设置该特性。

     

    最新回复(0)