Search code examples
c#asp.netentity-frameworkasp.net-web-apiin-memory-database

C# WEB API How to HttpPost with Parameter and how to httpsGet string and return custom List


I am doing a WEB API which generates a random Credit Card Number with the clients email.

First, how can I can, without Postman JSON code, Post the clients email and the credit card number and de ID just by https://localhost:44355/api/ClienteDados/"Typing the email here". This below is what I have so far. I manage to do it with Postman, but I want to do it in the URL.

My Class is ClienteDados.

Int ID

string EmailId

string NumCartao

My context is _context.

My DB is ApiContext and DbSet ClientesDB

[HttpPost("{email}")]
    public async Task<ActionResult<ClienteDados>> PostClienteDados(string email, ClienteDados clienteDados)
    {
        //Begin
        Random rnd = new Random();
        int cardNumber1 = rnd.Next(4572, 4999);
        int cardNumber2 = rnd.Next(1000, 9999);
        int cardNumber3 = rnd.Next(1000, 9999);
        int cardNumber4 = rnd.Next(1000, 9999);
        clienteDados.NumCartao = $"{cardNumber1} {cardNumber2} {cardNumber3} {cardNumber4}";
        clienteDados.EmailId = email;
        //End

        
        _context.ClientesDB.Add(clienteDados);
        await _context.SaveChangesAsync();


        return CreatedAtAction("GetClienteDados", new { id = clienteDados.NumCartao }, clienteDados.NumCartao);
    }

After I registred the clientes info with EF Inmemory, I want to make a HttpGet of all credit cards from the parameter EMAIL. So when they type /email/"email here" it show a LIST of all credit card numbers in that email.

How can I do the list, and how can I do the search by the string Email? all the time I can only search by int ID.

[HttpGet, Route("email/{email}")]
    public async Task<ActionResult<IEnumerable<ClienteDados>>> GetEmail(string email)
    {


        var cc = await _context.ClientesDB.FindAsync(email);

        return Ok(cc);

    }

The Https Get above does not work yet because it's a string, it only works with the int ID. Thank you very much in advance.

EDIT 1 So I managed to get the List by the url parameter, but its showing me the id, the email and the CC Number, how can I filter it just to CC number?

List<ClienteDados> list = await _context.ClientesDB.Where(a => a.EmailId.Equals(email)).ToListAsync();
       return Ok(list);

Solution

  • change this line:

    List<ClienteDados> list = await _context.ClientesDB.Where(a => a.EmailId.Equals(email)).ToListAsync();
       return Ok(list);
    

    to:

    var list = _context.ClientesDB.Where(a => a.EmailId.Equals(email)).Select(s => new { NumCartao  = s.NumCartao }).ToList();
       return Ok(list);