![](/img/trans.png)
[英]Convey FaultException details from an ajax-enabled WCF service?
[英]Ajax-Enabled WCF Service - implementing Observer Design Pattern
我創建了一個Notifications系統,每次有新通知時都會通知用戶。
目前在我的客戶端腳本中,我每秒都調用Web服務調用來ping服務器以獲取新通知。 如果有新的通知,我怎樣才能讓啟用Ajax的WCF通知客戶端?
有沒有人有任何資源,建議或教程來使用支持Ajax的WCF實現Observer設計模式?
*注意:使用Observer模式可能不是實現此方法的最佳方式,對最佳模式(可能是我當前的實現)的任何建議都非常感謝。
客戶端:
$(document).ready(function () {
self.setInterval("getNewNotificationsCount()", 1000);
});
function getNewNotificationsCount() {
$.ajax({
type: "POST",
url: site_root + "services/NotificationService.svc/json/GetNewNotificationsCount",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
error: function (request, error, u) {
alert('error: ' + error);
},
success: function (result, status) {
$('#hip_badge').text(result.d);
}
});}
通知服務
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class NotificationService {
{
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json)]
public int GetNewNotificationsCount()
{
NotificationManager nm = new NotificationManager();
return nm.getNewNotifications(GetUserName());
}
你喜歡使用WCF嗎? SignalR可能更適合這種推送通知。
更新:只是為了澄清; SignalR抽象了一種服務器將數據推送到多個客戶端的機制,其中一個客戶端是JavaScript。 在客戶端上,您可以掛鈎處理通知的事件處理程序, 因為它們是由通知管理器發送的...
干杯,迪恩
據我對Web模型的理解,服務器(WCF服務)無法在沒有客戶端請求通知的情況下通知客戶端(AJAX應用程序)。 這似乎是客戶端和服務器之間整個請求 - 響應系統的核心。
我知道您需要這樣才能使您的應用程序更有效率,並且有一些建議可能有所幫助:
POST
更改為GET
因為顯然,您不必在獲取通知時發送任何復雜數據。 在AJAX場景中, GET
比POST
更快。 這可以在新版本的WCF(4.5)中實現。 您可以使用Websockets與HTTP客戶端進行雙向通信。 你不會再使用AJAX,而是使用帶有websockets的javascript。 有關詳細信息,請查看以下鏈接: http : //www.codeproject.com/Articles/338789/What-s-new-in-WCF-4-5-WebSocket-support-Part-1-of
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.