简体   繁体   中英

Cannot process the message because the content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'

I am get the above response when calling a WCF service via ajax json. My calling code is:

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax
        ({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "http://localhost:90/WebServices/UserService.svc/Calculate",
            data: "{}",
            timeout: 10000,
            dataType: "json",
            success: function (response) {
                alert(response)
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.statusText);
                alert(thrownError);
            }
        });
    });
</script>

My service is:

[ServiceContract]
public interface IUserService
{
    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json
     )]
    Answer Calculate();
}

[DataContract]
public class Answer
{
    [DataMember]
    public string answer { get; set; }
}

My method is :

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class UserService : IUserService
{
    public Answer Calculate()
    {
        Answer answer = new Answer();
        answer.answer="Hello World";
        return answer;
    }
}

I have been battling with for sometime, I see other people have had the same type problem and I tried all there suggestions but still nothing is working.

Where is the problem? How can I solve it?

I'm guessing here since you didn't show how you defined your endpoint, but I'm pretty sure it's the case. Your endpoint is not defined for web consumption - it's likely using basicHttpBinding . To consume the endpoint via jQuery (or other web/REST clients in general) you need to define an endpoint with the WebHttpBinding , and apply the WebHttpBehavior to it.

There are different ways to define the endpoint correctly. The easiest one is to use the WebServiceHostFactory in your .svc file:

UserService.svc :

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

For anyone who lands here by searching: 'content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'

A similar error was caused in my case by building and running a service without proper attributes. I got this error message when I tried to update the service reference in my client application. It was resolved when I correctly applied '[DataContract]' and '[DataMember]' attributes to my custom classes.

Edit: This would most likely be applicable if your service was set up and working and then it broke after you edited it.

This is a pretty old question, but I'd like to add some information upon @carlosfigueira answer.

1. Specifying Factory in .svc vs. specifing a <service> in web.config

The alternative to specifying a Factory in the .svc file is specifying a <service> in the web.config file. This is explained in many other answers (eg this one ), so I won't repeat them, but it worth copying here yet another @carlosfigueira answer :

If you don't specify any factory in the .svc file, all the endpoints will come from the web.config file - WCF will try to find a <system.serviceModel / service> element whose name attribute matches the fully-qualified name of the service class. If it doesn't find one, then it will add a default endpoint (using basicHttpBinding , unless you changed the default mapping).

And to be clear: the fully-qualified name should include the namespace. So if one has the following, it would be MyWebServices.ExampleWebService :

namespace MyWebServices
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    public class ExampleWebService
    {
        [OperationContract]
        [WebInvoke(Method = "POST",
            BodyStyle = WebMessageBodyStyle.Bare,
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json)]
        public string DoWork(DoWorkRequest request)
        {
            return "success!";
        }
    }
}


2. Getting "Cannot process the message..." when called on localhost

I came to this question when trying to run an ajax call on localhost from Visual Studio, and got the error message which is the title of this question, so I'd like to list the required steps to solve it:

  1. As explained above, either add a Factory in the .svc , or specify what's needed in the web.config .
  2. In Visual Studio, right-click your .html file, and select "View in Browser". Your default browser would open, and if it's Chrome, the url would be, eg, localhost:51667/test.html (which is actually http://localhost:51667/test.html ).
  3. You can now fire your ajax call, and hopefully, you'd get your web service response successfully.
  4. If you'd like to debug your web service, then:
    In Visual Studio, make sure that the web service's project is set as the Startup Project, and hit F5. This would start WCF Test Client window, but you can just ignore it and fire your ajax request.

In my case the problem was the request method. I was trying to send GET request instead of POST request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question HTTP 415 Cannot process the message because the content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8' 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' Cannot process the message because the content type 'application / xml' was not the expected type 'application / soap + xml; charset = utf-8 ' The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8) The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8), WCF The content type text/xml; charset=“utf-8” of the response message does not match the content type of the binding (text/xml; charset=utf-8) The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8) WCF Membership Provider throws error: content type 'application/json; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8' WCF SOAP service cannot process the message because it sends multipart message and expects 'text/xml; charset=utf-8' The content type text/plain of the response message does not match the content type of the binding (text/xml; charset=utf-8)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM