❔ how to get city data from request body?

app.MapPost("/cities", async (DataContext dataContext) => {
dataContext.Cities.Add(city);
await dataContext.SaveChangesAsync();
return Results.Created();
});
app.MapPost("/cities", async (DataContext dataContext) => {
dataContext.Cities.Add(city);
await dataContext.SaveChangesAsync();
return Results.Created();
});
6 Replies
mg
mg15mo ago
Create a class to model the request body and add it as a parameter with the [FromBody] attribute
Timo Martinson
Timo MartinsonOP15mo ago
ok, so this will work:
app.MapPost("/cities", async ([FromBody] City city, DataContext dataContext) => {
dataContext.Cities.Add(city);
await dataContext.SaveChangesAsync();
return Results.Created();
});
app.MapPost("/cities", async ([FromBody] City city, DataContext dataContext) => {
dataContext.Cities.Add(city);
await dataContext.SaveChangesAsync();
return Results.Created();
});
... is that correct:
namespace GetOut.Models;

public class City(string slug, string name, string? description)
{
public Guid Id { get; set; } = Guid.NewGuid();

public DateTime CreatedAt { get; set; } = DateTime.Now;
public DateTime UpdatedAt { get; set; } = DateTime.Now;
public DateTime? DeletedAt { get; set; }

public string Slug { get; set; } = slug;
public string Name { get; set; } = name;
public string? Description { get; set; } = description;
}
namespace GetOut.Models;

public class City(string slug, string name, string? description)
{
public Guid Id { get; set; } = Guid.NewGuid();

public DateTime CreatedAt { get; set; } = DateTime.Now;
public DateTime UpdatedAt { get; set; } = DateTime.Now;
public DateTime? DeletedAt { get; set; }

public string Slug { get; set; } = slug;
public string Name { get; set; } = name;
public string? Description { get; set; } = description;
}
mg
mg15mo ago
$tias
mg
mg15mo ago
But also, you should be making a separate model for the request body Don't use your database model And you should also create a service class to encapsulate the logic of creating a city, and have your API endpoint call that service instead of using the database context itself
Accord
Accord15mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server