javascript +.net 构建restful API 应用

来源:互联网 发布:win7 64位数据库下载 编辑:程序博客网 时间:2024/06/06 05:10
1、利用.net 构建 restful API1)创建类库,将需要被调用和访问result API方法定义到类库中的接口和对象中,示例代码如下:[ServiceContract]    interface ITest    {        [OperationContract]        [WebGet(UriTemplate="test",ResponseFormat=WebMessageFormat.Json)]        SampleItem TestItem();    }注意:需要为接口增加ServiceContract属性,在接口方法中增加WebGet 属性,表示采用get方法访问,UriTemplate表示该方法访问的路径为xxxx/test,ResponseFormat属性表示数据返回方式;接口定义完毕后定义实现该接口的对象即可:public class Service : ITest    {        public SampleItem TestItem()        {            // TODO: Change the sample implementation here            SampleItem item = new SampleItem() { Value = "TestSample" };            return item;        }    }    // TODO: Modify the SampleItem. Use Visual Studio refactoring while modifying so that the references are updated.    /// <summary>Value    /// Sample type for the singleton resource.     /// By default all public properties are DataContract serializable    /// </summary>    [DataContract]    public class SampleItem    {        [DataMember]        public string Value { get; set; }    }注意:SampleItem是可以序列化的数据对象,该对象由系统自动根据接口方法定义属性,序列化为json格式或xml格式2)创建web空网站,编辑并修改web.config属性内容:在configuration节下增加如下配置内容:<system.serviceModel><serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"><serviceActivations><add relativeAddress="Service.svc" service="RestDemo.Service"/></serviceActivations></serviceHostingEnvironment><behaviors><serviceBehaviors><behavior name="testconfig"><serviceMetadata httpGetEnabled="true"/><serviceDebug includeExceptionDetailInFaults="true"/></behavior></serviceBehaviors><endpointBehaviors><behavior name="EndBehavior"><webHttp helpEnabled="true"/></behavior></endpointBehaviors></behaviors><services><service name="RestDemo.Service" behaviorConfiguration="testconfig"><endpoint address="" behaviorConfiguration="EndBehavior" binding="webHttpBinding" contract="RestDemo.ITest"/></service></services></system.serviceModel>主要增加了对服务模型及其服务行为和终结点等信息的定义;完成以上步骤后即可在浏览器中通过url直接访问result API方法,并查看调用反馈结果。2、利用 java script访问 restful API1)采用jquery访问,示例代码如下:<script type="text/javascript" src="JS/jquery.js"></script><script type="text/javascript" >$(document).ready(function(){   $.ajax({         type: "GET",         url: "Service.svc/test",         dataType: "json",         contentType: "application/json; charset=utf-8",         success: function(json)         {         alert(json.Value)         },         error: function(error) {             alert("调用出错" + error.responseText);         }    });});</script>注意:在java script中访问的API URL 必须和调用java script的网页属于同一个网站,否则可能出现访问异常;2)采用 ajax的方法访问,示例代码如下:function createXmlHttp(){var xmlhttp;if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();elsexmlhttp=new ActivexObject("Microsoft.XMLHTTP");  //IE 5或6 }function noCrossDomain(url){xmlHttp=createXmlHttp();xmlHttp.onreadystatechange=stateChange;xmlHttp.open("GET",url,true);xmlHttp.send(null);}function stateChange(){if (xmlHttp.readyState!=4)return;if (xmlHttp.status!=200)return ;alert(xmlHttp.responeText);}注意:在上述函数中 url 与xmlHttp均为全局变量,需要在调用函数的主页面中定义;
0 0
原创粉丝点击