打开VS 2013(或者其他版本),新建项目-WCF服务应用程序
删除自动生成的Service1.cs和IService1.cs,添加新建项
找到WCF服务,支持Ajax,添加该条目
右键web.config 编辑WCF配置,点击绑定右键新建绑定选择webHttpBinding,
更改一下name的名字,再将跨域访问改成true,maxbuffer等参数与上传文件的post服务有关,涉及到上传文件的大小,这里可以默认。
然后点击服务找到终结点,更改name,然后bindingConfiguration选择我们上一步建立的绑定点,
最后保存退出,这里主要是更改了webconfig里的配置内容,大家可以仔细查看配置文件的变化,可以手动更改配置,至此创建和配置告一段落。
下面我们开始写后台服务,打开service1.svc,加入代码:
namespace WcfService1
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
// 要使用 HTTP GET,请添加 [WebGet] 特性。(默认 ResponseFormat 为 WebMessageFormat.Json)
// 要创建返回 XML 的操作,
// 请添加 [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// 并在操作正文中包括以下行:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
public void DoWork()
{
// 在此处添加操作实现
return;
}
// 在此处添加更多操作并使用 [OperationContract] 标记它们
[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public string GetFun1(string UserID, int OperaID)
{
return UserID + OperaID;
}
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public string GetFun2(string UserID, int OperaID)
{
return UserID + OperaID;
}
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public string post1(string userid,string password)
{
return userid + password;
}
}
}
其中,我们添加了三个服务,两个get请求和一个post请求,get的两种写法是一样的作用,注意的是要求bodystyle关乎到前台ajax的数据封装,一般默认都是处理的,所以不用特意更改。responseFormat响应格式设为json,requestFormat请求格式设为json。
写好服务后,通过调试进入svc页面
出现以下页面即无问题
get请求的测试可以在浏览器中进行,那么在地址栏写入测试:
http://localhost:14483/Service1.svc/GetFun2?UserID=as&OperaID=23,返回结果
这里比较清晰的看到返回数据的形式,mircosoft会给响应的结果套一层壳子,返回的是{d: data}的json。针对套壳子的问题,可以后台序列化JSON之前就去掉,返回message格式。
post请求不能在浏览器中查看,我们新建一个页面,在js中使用ajax,如下:(只展示post的前台写法,get也可使用ajax,写法类似)
$.ajax({
url: "http://localhost:14483/Service1.svc/post1",
type: "post",
data: JSON.stringify({ userid: "001", password: "a" }),
dataType: 'json',
contentType: 'application/json;charset=utf-8',
async: false,
success: function (result) {
alert(result.d);
}
});
返回结果如下:
至此,WCF服务就写好了。下一篇将介绍图片上传的服务写法。