近几年比较流行restful,为了能让ajax调用,同时也为了支持restful风格的uri,在创建一个Ajax-enabled Wcf Service后,必须手动修改svc文件,指定Factory,即:
注:如果不添加Factory,则wcf将无法用类似http://localhost/helloWorld.svc/Hello/person/name 的restful方式直接访问。
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
namespace ajaxSample
{
[ServiceContract(Namespace = "http://yjmyzz.cnblogs.com/")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class HelloWorld
{
///
/// 只能Post的Restful方法
/// ///
///
///
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "PostRestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat.Json)]
public List
PostRestfulTest(string person,string welcome)
{
List result = new List();
result.Add("PostRestfulTest -> from server:");
result.Add(person);
result.Add(welcome);
return result;
}
///
/// 只能Get的Restful方法
///
///
///
///
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "GETRestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat.Json)]
public List GETRestfulTest(string person, string welcome)
{
List result = new List();
result.Add("GETRestfulTest -> from server:");
result.Add(person);
result.Add(welcome);
return result;
}
///
/// 即可Get与Post的Restful方法
///
///
///
///
[OperationContract]
[WebInvoke(Method = "*", UriTemplate = "RestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat.Json)]
public List RestfulTest(string person, string welcome)
{
List result = new List();
result.Add("RestfulTest -> from server:");
result.Add(person);
result.Add(welcome);
return result;
}
///
/// 只能Post的常规方法(注:Post方式,BodyStyle必须设置成WrappedRequest或Wrapped)
///
///
///
///
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.WrappedRequest)]
public List PostTest(string person, string welcome)
{
List result = new List();
result.Add("PostRestfulTest -> from server:");
result.Add(person);
result.Add(welcome);
return result;
}
///
/// 只能Get的常规方法
///
///
///
///
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
public List GETTest(string person, string welcome)
{
List result = new List();
result.Add("GETTest -> from server:");
result.Add(person);
result.Add(welcome);
return result;
}
}
}
有时候,WCF暴露的方法中可能需要一些敏感信息做为参数(比如用户名/用户ID之类),这时如果直接用js来调用wcf,可能会把这部分信息泄漏在客户端,这种场景下,我们也经常用一个服务端的ashx来做中转
using System.ServiceModel;
namespace ashx_jQuery
{
[ServiceContract]
public class TestService
{
///
/// 获取当前用户指定月份的工资
/// ///
///
///
[OperationContract]
public double GetSalary(int userId,int month)
{
if (month == 1)//只是演示而已
{
return 5000;
}
else
{
return 1000;
}
}
}
}