2012-07-13 127 views
8

我試圖從一個ASPX頁面調用WCF Web服務,像這樣調用WCF服務:

var payload = { 
    applicationKey: 40868578 
}; 

$.ajax({ 
    url: "/Services/AjaxSupportService.svc/ReNotify", 
    type: "POST", 
    data: JSON.stringify(payload), 
    contentType: "application/json", 
    dataType: "json" 
}); 

否則會導致Web服務器返回錯誤415 Unsupported Media Type。我敢肯定,這是一個配置問題,其定義如下WCF服務:

[OperationContract] 
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json)] 
void ReNotify(int applicationKey); 

有在web.config文件中沒有條目,假設服務使用的默認配置。

回答

4

我不是這方面的專家,實際上我有同樣的問題(因爲另一個原因)。但是,看起來WCF服務本質上並不支持AJAX,因此您的web.config文件中必須具有以下代碼才能啓用它。

<system.serviceModel> 
    <behaviors> 
     <endpointBehaviors> 
      <behavior name="NAMESPACE.AjaxAspNetAjaxBehavior"> 
       <enableWebScript /> 
      </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" 
     multipleSiteBindingsEnabled="true" /> 
    <services> 
     <service name="NAMESPACE.SERVICECLASS"> 
      <endpoint address="" behaviorConfiguration="NAMESPACE.AjaxAspNetAjaxBehavior" 
       binding="webHttpBinding" contract="NAMESPACE.SERVICECLASS" /> 
     </service> 
    </services> 
</system.serviceModel> 

,然後這

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.ServiceModel.Activation; 
using System.ServiceModel.Web; 
using System.Text; 

namespace NAMESPACE 
{ 
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)] 
    [ServiceContract(Namespace = "")] 
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
    public class SERVICECLASS 
    { 
     // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json) 
     // To create an operation that returns XML, 
     //  add [WebGet(ResponseFormat=WebMessageFormat.Xml)], 
     //  and include the following line in the operation body: 
     //   WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; 
     [OperationContract] 
     public string DoWork() 
     { 
      // Add your operation implementation here 
      return "Success"; 
     } 

     // Add more operations here and mark them with [OperationContract] 
    } 
} 

這是由VS 2012中產生什麼,當我增加了一個AJAX服務類啓用WCF服務。

相關問題