Send Json from client application and receive on Server

Asked

Viewed 699 times

0



I have a problem sending a json from my client application to my server API.
Json is generated correctly, and the POST request is made, but on the server side the following error is reported:

"message": "Ocorreu um erro.",
"exceptionMessage": "Não é possível associar o parâmetro 'dados_json'. É preciso especificar um binder de modelo personalizado para associar parâmetros do tipo 'StringContent'.",
"exceptionType": "System.InvalidOperationException",
"stackTrace": "   em System.Web.Http.Controllers.HttpActionBinding.ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)\r\n   em System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---\r\n   em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   em System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()"

The sending code of the Httppost request that runs client application is this:

 async void ExecuteSalvarCommand()
    {
        try
        {
            var stringDados = await Task.Run(() => JsonConvert.SerializeObject(data));
            var httpContent = new StringContent(stringDados, Encoding.UTF8, "application/json");

            using (var httpClient = new HttpClient())
            {

                // Do the actual request and await the response
                var httpResponse = await httpClient.PostAsync($"{ BaseUrl}salvar", httpContent);

                // If the response contains content we want to read it!
                if (httpResponse.IsSuccessStatusCode)
                {
                    await App.Current.MainPage.DisplayAlert("Tlab", "Dados cadastrados com sucesso!", "OK");
                    ClearXML();
                    NSerie = "";
                }
                else
                {
                    await App.Current.MainPage.DisplayAlert("Tlab", "Falha ao cadastrar dados, verifique sua conexão com a internet!", "OK");
                }
            }
        }

The code that receives the POST on the server is this:

 [HttpPost]
    [Route("salvar")]
    public HttpResponseMessage InsertorUpdate(StringContent dados_json)
    {
        if (Application.BD.Conectar())
            return Request.CreateResponse(HttpStatusCode.Created, Application.Querys.Insert(dados_json));
        else return Request.CreateResponse(HttpStatusCode.BadRequest, error);
    }


The object that receives the Json information sent by the client application is this:

    public class Relacao
{
    public int tap { get; set; }
    public double nominal { get; set; }
    public double medido { get; set; }
    public double ErroP { get; set; }
}

public class Identificador
{
    [JsonProperty("num_serie")]
    private string num_serie;

    [JsonProperty("condicao")]
    private string condicao;

    [JsonProperty("tipo_relacao")]
    private string tipo_rel;

    public string Tipo_rel { set => tipo_rel = value; }
    public string Condicao { set => condicao = value; }
    public string Num_serie { set => num_serie = value; }
}

//Gerar Json
public class Dados
{
    [JsonProperty("Identificador")]
    public Identificador identificador = new Identificador();

    [JsonProperty("objetos")]
    public ObservableCollection<Relacao> objetos { get; set; }
}
  • Amigo creates a class with all the properties of his JSON and where he receives the request instead of receiving a Stringcontent type puts his created class.

  • Got like this? [Httppost] [Route("save")] public Httpresponsemessage Insertorupdate(Data data_json) {&#xA; if (Application.BD.Conectar())&#xA; return Request.CreateResponse(HttpStatusCode.Created, Application.Querys.Insert(dados_json));&#xA; else return Request.CreateResponse(HttpStatusCode.BadRequest, error);&#xA; }

  • @Mayconf.Castro yes, yes. I found where I was wrong, I had put an improper override. I got the data, thank you very much! How do I mark your comment as a response? kk (Obs: I’m new here in the community)

  • The JSON keys are identical with the names you put in the annotate [Jsonproperty]???

  • @Mayconf.Castro edited the above comment. Gave straight, thank you very much!

  • Arthur I will put the comment as a response if possible please punctuate as a response.

  • @Mayconf.Castro, done. Grateful!

Show 2 more comments

1 answer

0


Amigo creates a class with all the properties of his JSON and where he receives the request instead of receiving a Stringcontent type puts his created class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.