Home > Software engineering >  unity post method send string but doesn't class object
unity post method send string but doesn't class object

Time:10-08

as you can see in the title this method send string but doesn't send my class object. this method is working correctly in windows form app. The method:

async public Task<bool> PostHttp()
{
    using (var client = new HttpClient())
    {
        RegModel model = new RegModel()
        {
            UserMail = "ca35",
            UserPass = "1111"
        };
        //string model = "denemeGe";
        client.BaseAddress = new Uri("http://localhost:5070/");
        string postData = JsonConvert.SerializeObject(model);
        //string postData = JsonUtility.ToJson(model);
        Debug.Log(postData);
        var content = new StringContent(postData, Encoding.UTF8, "application/json");
        var result = await client.PostAsync("api/doPost",content);

        string resultContent = await result.Content.ReadAsStringAsync();
        Debug.Log(resultContent);
        return true;
    }
}

my class:

   public class RegModel
{
    public string UserMail;
    public string UserPass;
}

and API:

[ApiController]
[Route("api/RemoteOperations")]
public class RegController : ControllerBase
{
    [HttpGet]
    [Route("/api/doGet")]
    public RegModel Get()
    {
        var _regModel = new RegModel()
        {
               UserMail = "deneme",
               UserPass ="denemepass"
        };

        return _regModel;
    }
    [HttpPost]
    [Route("/api/doPost")]
    public string Post(RegModel regModel)
    {
        string result = regModel.UserMail;

        return "ok "  result;
    }
}

When I try to post my model json debug like that:

{"UserMail":"ca35","UserPass":"1111"}

But RegModel.userMail and RegModel.userPass return null. what is the problem ?

CodePudding user response:

If you're using a new Web App server, and/or your server is using System.Text.Json as it's JSON serialiser, then you can resolve the issue in one of two ways:

The first is to use properties instead of fields. This can be an issue if your client side serialiser wants you to use fields instead of properties, in which case you'd need to define your model twice, once with fields on the client and the server side with properties:

public class RegModel
{
    public string UserMail { get; set; }
    public string UserPass { get; set; }
}

The second method is to allow System.Text.Json to read fields on the server by adding the JsonSerializerOptions.IncludeFields option:

// Add services to the container.
builder.Services.AddControllers ( )
    .AddJsonOptions ( options => options.JsonSerializerOptions.IncludeFields = true );

CodePudding user response:

Networks cannot send objects. You can convert the object to JSON or XML format and send it over the network. Prepare a model to receive data to the server and receive data using this model. I think you understand that

  • Related