无法处理消息,因为内容类型为’application / json; charset = utf-8’不是预期的类型’text / xml; 字符集= UTF-8′

通过ajax json调用WCF服务时,我得到了上述响应。 我的主叫代码是:

 $(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); } }); });  

我的服务是:

 [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; } } 

我的方法是:

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

我一直在与之斗争,我看到其他人有同样类型的问题,我尝试了所有的建议,但仍然没有任何工作。

问题出在哪儿? 我该如何解决?

我猜你在这里,因为你没有展示你如何定义你的端点,但我很确定是这样的。 您的端点未定义用于Web使用 – 它可能使用basicHttpBinding 。 要通过jQuery(或一般其他Web / REST客户端)使用端点,您需要使用WebHttpBinding定义端点,并将WebHttpBinding应用于它。

有不同的方法可以正确定义端点。 最简单的方法是在.svc文件中使用WebServiceHostFactory

UserService.svc

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

对于通过搜索来到这里的任何人:’内容类型’应用程序/ json; charset = utf-8’不是预期的类型’text / xml; 字符集= UTF-8′

在我的情况下,通过构建和运行没有适当属性的服务也会导致类似的错误。 当我尝试在客户端应用程序中更新服务引用时收到此错误消息。 当我正确地将'[DataContract]’和'[DataMember]’属性应用于我的自定义类时,它已得到解决。

编辑:如果您的服务已设置并正常工作,那么这很可能适用,然后在您编辑它之后它就会中断。