WCF服务邮政方法不起作用



当我使用另一个项目的AJAX调用WCF服务时,我会遇到以下错误:

服务器遇到了处理请求的错误。异常消息是"传入消息"具有意外的消息格式" RAW"。该操作的预期消息格式为" XML"," JSON"。这可能是因为尚未在绑定上配置WebContentTypemapper。有关更多详细信息,请参见WebContentTypemapper的文档。"。有关更多详细信息,请参见服务器日志。

我在项目中创建了以下WCF服务:

iservice1.cs -

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    int AddNumbers(int a);
    [OperationContract]
    string ShowMsg();
    // TODO: Add your service operations here
}

service1.cs-

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    public int AddNumbers(int a)
    {
        return a + 5;
    }
    [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    public string ShowMsg()
    {
        return "Hello World!";
    }
}

这就是我从另一个项目中消费它的方式:

$.ajax({
            type: "POST",
            url: "http://localhost:16748/Service1.svc/AddNumbers",
            contenType: 'application/json',
            data: JSON.stringify({ a: 4 }),
            dataType: 'json',
            success: function (data) {
                $("#elementsDiv").html(data);
            },
            error: function (xhr, status, error) {
                var err = xhr.responseText;
                $("#elementsDiv").html(err);
            }
        });

有人可以帮助我吗?

我相信您在Ajax呼叫中可能有错别字:

contenType: 'application/json',

我认为这应该是:

contentType: 'application/json',

除了您的代码对我运行不错。

最新更新