【发布时间】:2018-05-09 13:47:13
【问题描述】:
我正在尝试在 WCF 中使用“POST”方法,但我不能使用它,我可以在 WCF 服务中使用的唯一方法是“GET”方法,但是当我尝试使用“POST”时问题就开始了" 发送对象的方法:
这里有我的合同
[ServiceContract]
public interface Itest
{
[WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
[OperationContract]
string Hello();
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare )]
[OperationContract]
void AddObject(Person p);
[WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
[OperationContract]
string TurnBack(string Name);
}
我的对象:
namespace Mywcf
{
[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
}
}
我的实现:
namespace Mywcf
{
public class Implementacion : Itest
{
public string Hello()
{
return "Hi";
}
public void AddObject(Person p)
{
string Name = p.Name;
TurnBack(Name);
}
public string TurnBack(string Name)
{
return Name;
}
}
}
我的 .ASPX(包括我的脚本):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="scripts/jquery-3.2.1.js"></script>
<!--This SCRIPT Use my WCF as a 'GET'Method and works really good-->
<script>
$(document).ready(function() {
$("#btnHi").click(function() {
Hello();
});
});
function Hello() {
$.ajax({
url: "http://localhost:83/Mywcf/Service.svc/Hello",
dataType: "json",
data: "{}",
type: "GET",
contentType: "application/json; utf-8",
success: function(msg) {
try {
alert(msg);
} catch (Exception) {}
},
error: function(result) {
alert("Error " + result.status + '' + result.statusText);
}
});
}
</script>
<!--This SCRIPT has many issues (404 BAD REQUEST )I use the WCF as a 'POST' Method-->
<script>
$(document).ready(function() {
$("#btnConfirm").click(function() {
var name = $('#txtTest').val();
Insert(name);
});
});
function Insert(name) {
var objectPerson = {
"Name": name
};
var stringJ = JSON.stringify(objectPerson);
$.ajax({
url: "http://localhost:83/Mywcf/Service.svc/AddObject",
dataType: "json",
data: "{'p':" + stringJ + "}",
type: "POST",
contentType: "application/json; utf-8",
success: function(msg) {
try {
alert(msg);
} catch (Exception) {
alert(Exception);
}
},
error: function(result) {
alert("Error " + result.status + '' + result.statusText);
}
});
}
</script>
<title>TESTING WCF</title>
</head>
<body>
<input type="button" id="btnHi" value="Hello" /> <br />
<input type="text" id="txtTest" placeholder="Tip a Name" />
<input type="button" id="btnConfirm" value="Ok" />
</body>
</html>
我认为问题出在合同内的标头或我调用 AJAX 时。
【问题讨论】:
-
我有 404 错误说:“400 BAD REQUEST”
-
WCF 对于像 Javascript 这样的客户端通过 REST 调用的服务并不是最好的主意。您应该为此使用更专业的框架,例如 ASP.NET Web Api。
-
这里的问题是我正在学习软件编程,教授们希望使用 WCF...他们不允许这个项目使用 Web Api...#WhatAShame
-
修复您的代码 -
"application/json; utf-8"必须是"application/json; charset=utf-8" -
没错,它正在工作!!!非常感谢你:)
标签: javascript c# jquery ajax wcf