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

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

本文关键字:参数 对象 自定义 WebMethod      更新时间:2023-09-26

mycode:

对象:

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;
    }
}

页面(网络方法):

[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);
        }
    });
}

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

查看您提供的链接可能会注意到问题。

您的代码: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();
        }
    }

您正在从 webService 返回一个对象,但您在 ajax 中的内容类型是 json!您应该在两种方法中创建 json 格式的数据,并返回一个字符串 not object:

    [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