- 创建一个Wcf服务,如果是高版本的VS可以直接选择创建WCF服务(支持Ajax)。我这里是使用的VS2010
- 创建成功后删除所继承的接口并给服务加上特性
[ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
- 这里是用来测试所以是创建的两个方法分别返回两种数据格式
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public string Get()
{
return string.Format("You entered: {0}", "testData");
}
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public Message GetData(string str,Test test)
{
test.str += str;
return WebOperationContext.Current.CreateJsonResponse(test);
}
class Test
{
public string str { get; set; }
}
- 这里需要注意的地方是每个方法都需要加上“OperationContract”特性,如果是需要返回一个“干净的Json”则需要将返回的数据修改成Message类型并且用WebOperationContext.Current.CreateJsonResponse进行处理后再进行返回。
- 完整的服务代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;
using System.ServiceModel.Channels;
namespace WcfForPostMan
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public string Get()
{
return string.Format("You entered: {0}", "testData");
}
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public Message GetData(string str,Test test)
{
test.str += str;
return WebOperationContext.Current.CreateJsonResponse(test);
}
class Test
{
public string str { get; set; }
}
}
}
- 接下来是重点。配置Web.config
- config配置有两种方式,第一种是高版本VS才支持,第二种是手动在config中进行配置,这里先展示第二种手动配置的方式。
- 打开Web.config找到节点system.serviceModel节点并创建子节点services。
- 然后将子节点进行配置。
注意的点
- behaviorConfiguration:终结点名称与endpointBehaviors中的behavior 匹配
- binding: 与bindings中的webHttpBinding进行绑定
- name: service的name属性是命名空间.服务名称“WcfForPostMan.Service1”
- 第一种方式:
- 右键web.config文件选择WCF配置
- 将跨域设置为true,并设置名称
- 选择对应的属性,如果有默认的不需要调整
- 配置完成之后的效果
最终效果:
请求的“Content-Type”:“application/json; charset=utf-8”
Get方法(未处理返回格式):
GetData方法(处理返回格式):



