-1

I am very new to C# coding, or to coding at all, I am trying to create an API RESTFULL that when the user POST its email, it creates automatically a simples credit card number. I am at the very begging of the POST function.

// POST: api/Clientes

    [HttpPost]
    public async Task<ActionResult<Cliente>> PostCliente(Cliente cliente)
    {
        _context.Clientes.Add(cliente);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetCliente", new { id = cliente.Id }, cliente);
        
    }

So my question is, what is the code line that wil generate a 16 number and register in the api thru POST? thanks for the help in advance.

PART 2

Thanks for the solution, it partily worked. However, when i deploy it into Postman, even if I am able to register the ID - EMAIL - CREDIT CARD NUMBER (which is great, I am still geting an error message, the one below. Would you know how can I not get this message?

System.InvalidOperationException: No route matches the supplied values. at Microsoft.AspNetCore.Mvc.CreatedAtActionResult.OnFormatting(ActionContext context) at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsyncCore(ActionContext context, ObjectResult result, Type objectType, Object value)

(The message is too long for me to post all here)

1 Answers1

0

If you have a property "CreditCardNumber" in Cliente class, basically, you can write it in this way

[HttpPost]
public async Task<ActionResult<Cliente>> PostCliente(Cliente cliente)
{
    //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);
    cliente.CreditCardNumber = $"{cardNumber1} {cardNumber2} {cardNumber3} {cardNumber4}";
    //End
    _context.Clientes.Add(cliente);
    await _context.SaveChangesAsync();

    return CreatedAtAction("GetCliente", new { id = cliente.Id }, cliente);
    
}
Tunjay
  • 110
  • 3
  • 11
  • Thank you Tunjay for you reply, it helped me a lot. – user16039036 May 26 '21 at 15:54
  • However, when it deploy it into Postman, even if I am able to register the ID - EMAIL - CREDIT CARD NUMBER (which is great, I am still geting an error message, the one below. Would you know how can I not get this message? `System.InvalidOperationException: No route matches the supplied values. at Microsoft.AspNetCore.Mvc.CreatedAtActionResult.OnFormatting(ActionContext context) at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsyncCore(ActionContext context, ObjectResult result, Type objectType, Object value)` @Tunjay – user16039036 May 26 '21 at 15:58
  • Late answer, but lots of things can cause it, need to see the code – Tunjay May 29 '21 at 00:40