当我使用另一个项目的 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/