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

后端 未结 3 2054
别跟我提以往
别跟我提以往 2021-01-01 18:03

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



        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-01 18:58

    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 in web.config

    The alternative to specifying a Factory in the .svc file is specifying a in the web.config file. This is explained in many other answers (e.g. 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 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, e.g, 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.

提交回复
热议问题