创建一个可以用postman调用的WCF服务
- 创建一个Wcf服务,如果是高版本的VS可以直接选择创建WCF服务(支持Ajax)。我这里是使用的VS2010
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021050619274070.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3drejI1Njg=,size_16,color_FFFFFF,t_70)
- 创建成功后删除所继承的接口并给服务加上特性
[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>(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;