【问题标题】:WCF service POST method not workingWCF 服务 POST 方法不起作用
【发布时间】:2018-07-26 03:35:20
【问题描述】:

当我使用另一个项目中的 ajax 调用 wcf 服务时出现以下错误:

服务器在处理请求时遇到错误。异常消息是“传入消息具有意外消息格式“原始”。该操作的预期消息格式为“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);
            }
        });

谁能帮我解决这个问题?

【问题讨论】:

    标签: javascript c# asp.net ajax wcf


    【解决方案1】:

    我相信您的 ajax 调用中可能有错字:

    contenType: 'application/json',
    

    我认为应该是:

    contentType: 'application/json',
    

    除了你的代码对我来说运行良好。

    【讨论】:

      猜你喜欢
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多