我想将JSON数据发送到我的WCF服务,但在服务中,我的对象始终为null。我读了这么多文章,但我无法解决我的问题。
[WebInvoke(UriTemplate = "/POST/PersonPost", Method = "POST",BodyStyle=WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public Person InsertPerson(Person per)
{ Debug.WriteLine("InsertPerson");
if (per == null)
{
return new Person("2", "null");
}
Debug.WriteLine("POST:[PersonId = {0} PersonName = {1}]", per.Id, per.Name);
return new Person("1", "InsertPerson");
}
[DataContract]
public class Person
{
public Person(string id, string name)
{
this.id = id;
this.name = name;
}
[DataMember]
public string Id { get; set; }
[DataMember]
public string Name { get; set; }
public override string ToString()
{
var json = JsonConvert.SerializeObject(this);
return json.ToString();
}
}
这里是我的jQuery:
var person = {};
person.Id = "abc123";
person.Name = "aaaa";
var per = {};
per.per = person;
var param = JSON.stringify(per);
//param = "{"per":{"Id":"abc123","Name":"aaaa"}}"
$.support.cors = true;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: param,
dataType: "json",
processData: false,
crossDomain: true,
url: "http://localhost:59291/Person/POST/PersonPost",
success: function (data) {
alert("Post erfolgreich: ");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Fehler Post: Status " + xhr.status + " AntwortText " + xhr.responseText);
}
});
有什么问题?为什么insertPerson方法中的参数per始终为null。
答案 0 :(得分:2)
对不起我的英语,这项工作对我来说:
var LstPerson = new Array();
var person = {};
person.Id = 1
person.name = 'abc'
LstPerson.push(person)
var param = JSON.stringify(LstPerson);
仅从JS发送[{“id”:“1”,“name”:“abc”}]和WCF REST定义:
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
public Person InsertPerson(List<Person> per)
答案 1 :(得分:1)
这不起作用的原因是因为DataMember
是id
和name
而不是Id
和Name
。您需要修改以下代码:
person.Id = "abc123";
person.Name = "aaaa";
var per = {};
per.per = person;
到
person.id = "abc123";
person.name = "aaaa";
var per = {};
per.per = person;
答案 2 :(得分:0)
您的网站正在打破Same Origin Policy
Heres Ways to circumvent the same-origin policy
您设置crossDomain到true
,但这只与jsonp兼容,read this
答案 3 :(得分:0)
试试这个:
var person = {};
person.id = "1";
person.name = "abc";
var param = JSON.stringify(person);
其中一个原因是,您将请求对象作为null接收,因为该方法期望Person类型的对象。根据您对Person的定义,JSON中的内容如下所示。
{"id": "1", "name": "abc"}
这是因为每个人内部都没有。
Person person = New Person("1", "abc");
person.per //There is nothing defined as per inside person.