How to "read" return messages ASP.NET CORE WEB API

Asked

Viewed 379 times

1

I see here numerous questions about how to create custom feedback in a WEB API using ASP.NET Core. My question, besides this is the client side, how this message can be read in the application that will consume the services. For example: the user is registering a new item in a database where the description cannot be repeated. How to return a message and how to read this message to present it to the user, if they try to inform an item that already exists?

I’m trying this way:

MODEL

namespace ComandinhaAPI.Models
{
   public class TipoCardapio
   {
       [Key]
       public int TipoId { get; set; }
       public string Descricao { get; set; }
   }
}

API ASP.NET - Controller

[HttpPost]
public IActionResult Create([FromBody] TipoCardapio tipoCardapio)
{
        if(tipoCardapio==null)
            return BadRequest("Necessário informar os dados do tipo!");

        string nomeUpper = tipoCardapio.Descricao.ToUpper();
        tipoCardapio.Descricao = nomeUpper;

        if(_tRepositorio.BuscaPorDescricao(tipoCardapio.Descricao) != null)

            return BadRequest("Já existe um tipo com essa descrição!");

        _tRepositorio.Add(tipoCardapio);

CLIENT - WINDOWS FORMS - HTTPCLIENT

using (var client = new HttpClient())
{
   var serializedTipo = JsonConvert.SerializeObject(tipoCardapio);
   var content = new StringContent(serializedTipo, Encoding.UTF8, 
   "application/json");
   var result = await client.PostAsync(apiUrl, content);

   if (!result.IsSuccessStatusCode)
   {
       MessageBox.Show("Falha ao salvar o Tipo do Cardápio : \n" +
                        result.StatusCode.ToString() + " : " + 
                        result.ReasonPhrase.ToString(), "Tipos do Cardápio", 
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
   }
}
GetAllTipoCardapios();

I don’t know if this is the right way, but when I see the application running in debug mode I can read the messages returned in "result", but I can’t display them to the user.

There is another way to return and read API responses ?

  • It is possible to insert your object, so you can elaborate a response?

  • @Connection Sorry for my ignorance, but what would the object be? I edited the question, added my MODEL to it. What I want is to read the API response, if it returns me a 404 - Not Found. And along with this message comes a personalized message: Type does not exist in the register.

  • Its object would be the TipoCardapio who receives by parameter. if you received a 404 means that your request did not find the Endpoint of the api you are calling, reasons can be multiple, your object you are passing is not valid, the url to request is wrong. the tipoCardapio is null.

  • @I don’t think you could explain it to me. What I want is to know how to read in the client in C# the return of the messages that we put together with the response of the API, for example: 400 is code of BAD REQUEST, then we return return BadRequest("Já existe um registro com esta descrição!"); The forums and blogs only talk about how to create the API but how to receive and interpret the answer no! They talk a lot to use POSTMAN for testing, but he does everything himself, we do not see the code of how to do to have base.

  • I get it, I’m gonna come up with an answer that might help

1 answer

0

In that case, I strongly recommend the library Restsharp that already makes the work of deserialization of the object for you, what you need to do is in your client have the similar object, in your case:

public class TipoCardapio
{
   [Key]
   public int TipoId { get; set; }
   public string Descricao { get; set; }
}

Where your call would be something with:

var client = new RestClient("URL");

var request = new RestRequest("Endpoint", Method.POST);
request.AddJsonBody(tipoCardatio); 

request.AddHeader("header", "value"); //Caso tenha algum Header

var response = client.Execute<TipoCardapio>(request);
  • I’m trying to use only the components of .NET. A way to read the answers without using the Restsharp was that: string responseBody = await result.Content.ReadAsStringAsync() I see the contents of this message in accordance with Statuscode returned. The Restsharp do not know, but I will research and improve my knowledge. I thank for the collaboration.

  • That’s right, the return comes within Content, what you can improve in your code is to abstract the header and serialization by making a Factory. It has this very good example code: https://github.com/TahirNaushad/Fiver.Api.HttpClient

Browser other questions tagged

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