javascript - WCF 服务 POST 方法不起作用

标签 javascript c# asp.net ajax wcf

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

服务器在处理请求时遇到错误。异常消息是“传入消息具有意外的消息格式‘Raw’”。该操作的预期消息格式为“Xml”、“Json”。这可能是因为尚未在绑定(bind)上配置 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',

除此之外,您的代码对我来说运行良好。

关于javascript - WCF 服务 POST 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48806218/

相关文章:

c# - WCF设计原则: Is it a good idea to edit auto-generated proxy classes?

c# - 为什么 char '\"' 与 char '"' 相同?

asp.net - 与 ASP.NET 项目中的网页设计师协作(使用 SVN)

c# - Malscript 注入(inject) SQL Server 2005 数据库

asp.net - 如何阻止来自同一 IP 的多个请求

javascript - 如何绑定(bind) desIndex 对 angular-ui-tree 中的值进行排序?

javascript - 在 D2L 主题中按角色发布内容

javascript - 如何从 Kaizala API 获取 accessToken

c# - Silverlight,如何制作UserControl列表(在ContentControl中?)

javascript - Object.freeze() 卡住原型(prototype)实例?