使用WCF开发REST服务

要点

  • 采用WebHttpBinding。
  • 加入WebHttpBehavior。
  • 若要跨域访问,要设置CrossDomainScriptAccessEnabled属性为true。不要设置其它的,如:JavascriptCallbackBehavior、enableWebScript 、AspNetCompatibilityRequirements等
  • 使用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为例)

REST WCF

posted @ 2012-08-17 16:16  beta2013  阅读(217)  评论(0编辑  收藏  举报