http://www.cnblogs.com/dudu/archive/2011/01/19/1939094.html
wcf contract
using System.ServiceModel;
using System.ServiceModel.Activation;
...
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class HelloService
{
[OperationContract]
public string Say(string word)
{
return string.Format("You say \"{0}\".", word);
}
}
這裡需要注意的是AspNetCompatibilityRequirements,如果不進行這個設定,WCF就不走ASP.NET管線,ASP.NET的上下文資訊就拿不到,比如:不加這個設定,HttpContext.Current就為null,最常用的情境就是根據HttpContext擷取使用者登入資訊,對使用者權限進行驗證。對應於這個設定,在
web.config的<system.serviceModel>中需要加上<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
Web.Config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"></serviceHostingEnvironment>
</system.serviceModel>
*注意的地方:web.config中加了上面的設定後,所有的WCF服務實現都要設定AspNetCompatibilityRequirements屬性。
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
<serviceActivations>
<add relativeAddress ="HelloService.svc" service="jQueryWCFDemo.HelloService"
factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"/>
</serviceActivations>
</serviceHostingEnvironment>
</system.serviceModel>
System.ServiceModel.Activation.WebScriptServiceHostFactory
在可動態啟用服務的主機執行個體以響應傳入訊息的託管宿主環境下,能夠向該服務中自動添加 ASP.NET AJAX 終結點而無需進行配置。
relativeAddress就是WCF服務的地址名,service就是之前建立的HelloService類名,factory是關鍵,支援ajax調用,靠的就是System.ServiceModel.Activation.WebScriptServiceHostFactory。
default.aspx
<script type="text/javascript">
function submit_word() {
$.ajaxSettings.url = 'HelloService.svc/Say';
$.ajaxSettings.type = 'post';
$.ajaxSettings.dataType = 'json';
$.ajaxSettings.contentType = 'application/json';
$.ajaxSettings.data = '{"word":"Hello,word"}';
$.ajaxSettings.success = function (data) {
alert(data.d);
};
$.ajax();
};
</script>
<input id="showmsg" type="button" value="show" onclick="submit_word()" />