I am trying to build a WCF service that accepts and returns data in json format and use it in ajax calls. The problem I am having is that when I attempt to call the WCF-service from javascript I get an 405 (Method Not Allowed) error. It seems that the web page calls options method on the server (OPTIONS localhost:49572/Service1.svc/testmethod HTTP/1.1) to which the server responds with the 405 statuscode.
Below is my service definition
namespace JsonAjaxService { [ServiceContract] public interface IService1 { [OperationContract] [System.ServiceModel.Web.WebInvoke( Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "testmethod")] CompositeType GetDataUsingDataContract(CompositeType composite); } [DataContract] public class CompositeType { bool boolValue = true; string stringValue = "Hello "; [DataMember] public bool BoolValue { get { return boolValue; } set { boolValue = value; } } [DataMember] public string StringValue { get { return stringValue; } set { stringValue = value; } } } }
And here is the Web.config
<?xml version="1.0"?> <configuration> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.5.1" /> <httpRuntime targetFramework="4.5.1"/> </system.web> <system.serviceModel> <services> <service name="JsonAjaxService.Service1" behaviorConfiguration="ServiceBehaviour"> <endpoint address ="" binding="webHttpBinding" contract="JsonAjaxService.IService1" behaviorConfiguration="web"> </endpoint> </service> </services> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> <behavior name="ServiceBehaviour"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="web"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <protocolMapping> <add binding="basicHttpsBinding" scheme="https" /> </protocolMapping> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <directoryBrowse enabled="true"/> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> </customHeaders> </httpProtocol> </system.webServer> </configuration> And finally the code I use to call this service
function test() { var json = '{"StringValue":"test","BoolValue":"false"}'; $.ajax( { type: "POST", processData: false, contentType: "application/json", url: "http://localhost:49572/Service1.svc/testmethod", data: json, dataType: "json", success: function (data) { alert(data); }, error: function (data) { alert('error')); } });