Rotas (Simples)

<< Click to Display Table of Contents >>

Navigation:  .NET 6 > WebApplication >

Rotas (Simples)

Previous pageReturn to chapter overviewNext page

Crie um novo projeto "ASP.NET Core Empty"

 

Program.cs

 

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

 

app.Use(async (context, next) =>

{

  await next(context);

 

  if (context.Response.StatusCode == 404)

   {

      await context.Response.WriteAsync("404-Pagina nao localizada");

   }

});

 

app.MapGet("/pizzas/{id}", (int id) => PizzaDB.GetPizza(id));

app.MapGet("/pizzas", () => PizzaDB.GetPizzas());

app.MapPost("/pizzas", (Pizza pizza) => PizzaDB.NovaPizza(pizza));

app.MapPut("/pizzas", (Pizza pizza) => PizzaDB.AtualizarPizza(pizza));

app.MapDelete("/pizzas/{id}", (int id) => PizzaDB.RemovePizza(id));

 

app.Run();

 

PizzaDB.cs

 

public record Pizza

{

  public int Id { get; set; }

  public string? Nome { get; set; }

  public decimal Valor { get; set; }

}

 

public class PizzaDB

{

  private static List<Pizza> _pizzas = new List<Pizza>()

  {

    new Pizza{ Id=1, Nome="Camarão", Valor=89.99M },

    new Pizza{ Id=2, Nome="Da Casa", Valor=105.05M},

    new Pizza{ Id=3, Nome="Margerita", Valor=56.11M}

  };

 

  public static List<Pizza> GetPizzas()

   {

      return _pizzas;

   }

 

  public static Pizza? GetPizza(int id)

   {

      return _pizzas.SingleOrDefault(pizza => pizza.Id == id);

   }

 

  public static Pizza NovaPizza(Pizza pizza)

   {

       _pizzas.Add(pizza);

      return pizza;

   }

 

  public static Pizza AtualizarPizza(Pizza update)

   {

       _pizzas = _pizzas.Select(pizza =>

       {

          if (pizza.Id == update.Id)

           {

               pizza.Nome = update.Nome;

               pizza.Valor = update.Valor;

           }

 

          return pizza;

       }).ToList();

 

      return update;

   }

 

  public static void RemovePizza(int id)

   {

       _pizzas = _pizzas.FindAll(pizza => pizza.Id != id).ToList();

   }

}