C# WebMethod - 发送和接收相同的自定义对象作为参数

C# WebMethod - Send and receive same custom object as parameter

我的代码:

对象:

public class Person
{

    private string _Nome;
    private DateTime _Nascimento;

    public string Nome { get { return _Nome; } }
    public DateTime Nascimento { get { return _Nascimento; } }

    public Person(string Nome, DateTime Nascimento)
    {
        _Nome = Nome;
        _Nascimento = Nascimento;
    }

}

页面(WebMethods):

[WebMethod]
public static Person SendPerson()
{
    return new Person("Jhon Snow", DateTime.Now);
}

[WebMethod]
public static string ReceivePerson(Person oPerson)
{
    return "OK!";
}

javascript:

var Person;
GetPerson();
SendPersonBack();
function GetPerson()
{
    $.ajax({
        type: "POST",
        url: "frmVenda.aspx/SendPerson",
        data: {},
        contentType: "application/json; charset=utf-8",
        success: function (RequestReturn) {
            Person = RequestReturn.d;
            console.log(Person);
        },
        error: function (error) {
            alert(error.statusText);
        }
    });
}
function SendPersonBack()
{
    $.ajax({
        type: "POST",
        url: "frmVenda.aspx/ReceivePerson",
        data: JSON.stringify({"oPerson": Person}),
        contentType: "application/json; charset=utf-8",
        success: function (RequestReturn) {
            alert(RequestReturn.d);
        },
        error: function (error) {
            alert(error.statusText);
        }
    });
}

我正常发送对象到客户端,但无法接收回服务器。 如果对象和它们的属性相同,为什么不能接收回来。 问题出在哪里?

您正在 return 从 webService 中获取一个对象,但是您在 ajax 中的内容类型是 json!您应该在两种方法中以 json 格式创建数据,并且 return 字符串不是对象:

    [WebMethod]
    public static static SendPerson()
    {
        JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
        return TheSerializer.Serialize(new Person("Jhon Snow", DateTime.Now));
    }

对于第二种方法,只需从 ajax 中删除内容类型或将其替换为:

application/x-www-form-urlencoded; charset=UTF-8

查看您提供的link可能会发现问题。

您的代码:data: JSON.stringify({"oPerson": Person}),

右码:数据:"{oPerson:" + JSON.stringify(Person) + "}",

在我看来,您向服务器发送的格式错误Json

此外,尝试将 dataType: 'json' 添加到您的通话中。

我通过创建一个不带参数的构造函数、将所有属性设置为字符串并在我的自定义对象 (Person) 的所有属性上添加 set 方法解决了这个问题。

 public class Person
    {

        private string _Nome;
        private string _Nascimento;

        public string Nome { get { return _Nome; } set { _Nome = value; } }
        public string Nascimento { get { return _Nascimento; } set { _Nascimento= value; } }

        public Person()
        {

        }

        public Person(string Nome, DateTime Nascimento)
        {
            _Nome = Nome;
            _Nascimento = Nascimento.ToString();
        }

    }