C# – HTTP/1.1 415 Cannot process the message because the content type ‘application/json; charset=utf-8’ was not the expected type ‘text/xml; charset=utf-8’

cwcf

trying to POST json dictionary to C# WCF, when i invoke it HTTP Response 415. Someone can tell me whats wrong with my code.

object Class

 [DataContract]
public class Class1
{
    [DataMember]
    public string AccNo;
     [DataMember]
    public string CompanyName;
     [DataMember]
    public string DocDate;
}

IService1.cs

   [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "json/PostSalesOrderData", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        string PostSalesOrderData(string data);

Service1.svc.cs

 public string PostSalesOrderData(string data)
    {

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        Dictionary<string, Class1> dict = serializer.Deserialize<Dictionary<string, Class1>>(data);

        return dict["Debtor"].AccNo.ToString();
    }

Fiddle Details

HTTP/1.1 415 Cannot process the message because the content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'.
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Thu, 29 Nov 2012 01:21:55 GMT
Content-Length: 0

Best Answer

The endpoint for your service is not properly configured to receive JSON input. In order for the [WebInvoke] attribute to be honored, your endpoint needs to have the webHttpBinding, and it should also have an endpoint behavior of type <webHttp/>

One easy way to ensure that it's properly configured is to use the Factory attribute on the .svc file. Something like the example below:

<%@ ServiceHost Language="C#" Debug="true"
                Service="YourNamespace.YourServiceClass"
                Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
Related Topic