Customize Json consumption - Web API

Asked

Viewed 145 times

2

I have the following information on Json:

[
  {
    "$id": "1",
    "Cditemcontacli": 1.0,
    "Cdcontacli": 1.0,
    "Descricao": "Produto 1"
  },
  {
    "$id": "2",
    "Cditemcontacli": 2.0,
    "Cdcontacli": 2.0,
    "Descricao": "Produto 2"
  },
  {
    "$id": "3",
    "Cditemcontacli": 3.0,
    "Cdcontacli": 2.0,
    "Descricao": "Produto 3"
  },
  {
    "$id": "4",
    "Cditemcontacli": 4.0,
    "Cdcontacli": 3.0,
    "Descricao": "Produto 4"
  }]

Controller:

//GET: api/Itemcontaclis/5
        [ResponseType(typeof(Itemcontacli))]
        public async Task<IHttpActionResult> GetItemcontacli(decimal id)
        {
            Itemcontacli itemcontacli = await db.Itemcontacli.FindAsync(id);
            if (itemcontacli == null)
            {
                return NotFound();
            }

            return Ok(itemcontacli);
        }

Web Api config:

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{Action}/{id}",
                defaults: new { id = RouteParameter.Optional }

I want to bring only those who have Cdcontacli:2.0. If you observe the Cdcontacli:2.0 repeats itself. Is it possible to search for the two together somehow? Thank you.

  • What is the structure of the Itemcontacli class in C#?

  • Excuse my ignorance, you mean this? public partial class Itemcontacli { public decimal Cditemcontacli { get; set; } public decimal Cdcontacli { get; set; public string Description { get; set; }

  • Is that exactly right, your Findasync database search method that receives an ID has no method that returns all items? Without necessarily needing an ID? Because you can’t help yourself, we need more information. Which database are you using? Where does this Findasync method come from? I ask this because there are N ways to solve this that you want to do, we need this information to be able to guide you in the best of them.

  • There is the method that returns all items, I did not publish because I thought it would not be necessary. But I think I can solve it differently. Still I will edit the question and publish the method. Thanks @Erickgallani.

1 answer

0


Solved with the following code implemented in the controller:

// GET: api/Itemcontaclis/cdContaCli
        public async Task<IHttpActionResult> GetPelaConta(decimal idContaCli)
        {
            return Ok(await db.Itemcontacli.Where(x => x.Cdcontacli == idContaCli).ToListAsync());
        }

Browser other questions tagged

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