读书人

施用WCF开发REST服务

发布时间: 2012-09-11 10:49:03 作者: rapoo

使用WCF开发REST服务
要点采用WebHttpBinding。加入WebHttpBehavior。若要跨域访问,要设置CrossDomainScriptAccessEnabled属性为true。不要设置其它的,如:JavascriptCallbackBehavior、enableWebScript 、AspNetCompatibilityRequirements等ajax访问时,dataType使用jasonp。只支持GET方式的跨域访问。使用Fiddler进行测试



服务契约示例
    [Description("测试")]    [ServiceContract]    public interface IAccountJsonService : INotSecuredServiceContract    {        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]        List<Account> GetAccountDataByGet();        [WebInvoke(Method = "POST")]        List<Account> GetAccountDataByPost();        /// <example>调用方式:/SendMessageByGet1?message=aaa&value=3</example>        [WebInvoke(Method = "GET")]        string SendMessageByGet1(string message, string value);        /// <example>调用方式:/SendMessageByGet/aaa/3</example>        [WebInvoke(Method = "GET", UriTemplate = "/SendMessageByGet2/{message}/{value}")]        string SendMessageByGet2(string message, string value);        /// <example>调用方式:{"message":"aa","value":3}。另外不要忘了在HTTP头中加入“content-type: text/json content-length: 26”。BodyStyle特性:方法参数若是多个,必须对其进行Json包装</example>        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedRequest)]        string SendMessageByPost(string message, int value);    }




参考

一个通过JSONP跨域调用WCF REST服务的例子(以jQuery为例)

读书人网 >其他相关

热点推荐