2012-07-13 12 views
8

Sto tentando di chiamare un servizio Web WCF da una pagina ASPX in questo modo:

var payload = { 
    applicationKey: 40868578 
}; 

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

In questo modo i risultati del web server restituendo l'errore 415 Unsupported Media Type. Sono sicuro che questo è un problema di configurazione con il servizio WCF che è definito come segue:

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

ci sono voci nel file web.config così scontato che il servizio utilizza la configurazione predefinita.

risposta

4

Non sono esperto in questo, infatti ho avuto lo stesso problema (per un altro motivo). Tuttavia, sembra che i servizi WCF non supportino intrinsecamente AJAX e pertanto è necessario il seguente codice nel file web.config per abilitarlo.

<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> 

e poi questo nella classe di servizio

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] 
    } 
} 

Questo è ciò che è stato generato da VS 2012, quando ho aggiunto un AJAX abilitato servizio WCF.

Problemi correlati