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

Mar*_*k C 15 c# ajax wcf

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

<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>
Run Code Online (Sandbox Code Playgroud)

我的服务是:

[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; }
}
Run Code Online (Sandbox Code Playgroud)

我的方法是:

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

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

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

car*_*ira 19

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

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

UserService.svc:

<%@ ServiceHost Language="C#" Debug="true" Service="YourNamespace.UserService"
                Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
Run Code Online (Sandbox Code Playgroud)