C
C#•13mo ago
Draggo

Put and Delete Methods not working.

Program.cs: using InventoryPro.Database; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); builder.Services.AddDbContext<InventoryDbContext>(options => options.UseInMemoryDatabase("InventoryDatabase")); var app = builder.Build(); app.Urls.Add("http://localhost:5555"); app.UseHttpsRedirection(); http: @WebApiHost = http://localhost:5555 GET {{WebApiHost}}/ ### GET {{WebApiHost}}/items ### POST {{WebApiHost}}/items Content-Type: application/json { "Name" : "Example item 3", "Description": "Description 3", "Price": 25.50, "Quantity": 30 } GET {{WebApiHost}}/items/1 ### PUT {{WebApiHost}}/items Content-Type: application/json { "itemId" : 1, "Name" : "Example item 1", "Description": "Description 1", "Price": 25.50, "Quantity": 30 } ### DELETE {{WebApiHost}}/items/1 using (var scope = app.Services.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService<InventoryDbContext>(); if (!dbContext.Items.Any()) { dbContext.Items.AddRange( new Item { Name = "Example Item 1", Description = "Description 1", Price = 10, Quantity = 100 }, new Item { Name = "Example Item 2", Description = "Description 2", Price = 20, Quantity = 50 } ); dbContext.SaveChanges(); } } app.MapGet("/items", async (InventoryDbContext dbContext) => await dbContext.Items.ToListAsync()); //app.MapGet("/items/{id}", async (int id, InventoryDbContext dbContext) => // await dbContext.Items.FindAsync(id) ?? Results.NotFound()); app.MapPost("/items", async (Item newItem, InventoryDbContext dbContext) => { dbContext.Items.Add(newItem); await dbContext.SaveChangesAsync(); return Results.Created($"/items/{newItem.ItemId}", newItem); }); app.MapPut("/items/{itemId}", async (int itemId, Item updatedItem, InventoryDbContext dbContext) => { var item = await dbContext.Items.FindAsync(itemId); if (item == null) return Results.NotFound(); item.Name = updatedItem.Name; item.Description = updatedItem.Description; item.Price = updatedItem.Price; item.Quantity = updatedItem.Quantity; await dbContext.SaveChangesAsync(); return Results.NoContent(); }); app.MapDelete("/items/{id}", async (int id, InventoryDbContext dbContext) => { var item = await dbContext.Items.FindAsync(id); if (item == null) return Results.NotFound(); dbContext.Items.Remove(item); await dbContext.SaveChangesAsync(); return Results.NoContent(); }); app.Run();
No description
98 Replies
tera
tera•13mo ago
which request did you execute exactly to get that response also $codegif
tera
tera•13mo ago
$code
MODiX
MODiX•13mo ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
Draggo
DraggoOP•13mo ago
Put and delete
tera
tera•13mo ago
and what url
Draggo
DraggoOP•13mo ago
PUT {{WebApiHost}}/items
Content-Type: application/json

{
"itemId" : 1,
"Name" : "Example item 1",
"Description": "Description 1",
"Price": 25.50,
"Quantity": 30
}
DELETE {{WebApiHost}}/items/1
PUT {{WebApiHost}}/items
Content-Type: application/json

{
"itemId" : 1,
"Name" : "Example item 1",
"Description": "Description 1",
"Price": 25.50,
"Quantity": 30
}
DELETE {{WebApiHost}}/items/1
Url is @WebApiHost = http://localhost:5005 this?
tera
tera•13mo ago
PUT {{WebApiHost}}/items
No description
tera
tera•13mo ago
this is not the same you're missing itemId in the url do PUT {{WebApiHost}}/items/1 for example
Draggo
DraggoOP•13mo ago
alright let me try same issue i think i had that on delete already too its the same error for both i think
tera
tera•13mo ago
are you familiar with curl?
Draggo
DraggoOP•13mo ago
im not
tera
tera•13mo ago
i have a feeling you're not executing the request you think you are
Draggo
DraggoOP•13mo ago
hmmm ok, so what does that mean?
tera
tera•13mo ago
curl -i "http://localhost:5555/items/1" -X PUT -d '{"itemId":1,"Name":"Exampleitem1","Description":"Description1","Price":25.50,"Quantity":30}' -H "content-type: application/json"
curl -i "http://localhost:5555/items/1" -X PUT -d '{"itemId":1,"Name":"Exampleitem1","Description":"Description1","Price":25.50,"Quantity":30}' -H "content-type: application/json"
run this in terminal see what you get
Draggo
DraggoOP•13mo ago
No description
tera
tera•13mo ago
aa 😬
Draggo
DraggoOP•13mo ago
🄺
tera
tera•13mo ago
Invoke-WebRequest -Uri "http://localhost:5555/items/1" `
-Method Put `
-ContentType "application/json" `
-Body "{`"itemId`":1,`"Name`":`"Exampleitem1`",`"Description`":`"Description1`",`"Price`":25.50,`"Quantity`":30}"
Invoke-WebRequest -Uri "http://localhost:5555/items/1" `
-Method Put `
-ContentType "application/json" `
-Body "{`"itemId`":1,`"Name`":`"Exampleitem1`",`"Description`":`"Description1`",`"Price`":25.50,`"Quantity`":30}"
or if you are familiar with postman/some other tool..
Draggo
DraggoOP•13mo ago
No but i think i changed my localhost let me retry someting nvm same error
tera
tera•13mo ago
with this ?
Draggo
DraggoOP•13mo ago
run this in terminal?
tera
tera•13mo ago
yes
Draggo
DraggoOP•13mo ago
No description
tera
tera•13mo ago
šŸ˜„ so the issue is with how you are executing the requests which editor/tool are you using to do it vs? rider?
Draggo
DraggoOP•13mo ago
visual studio code
tera
tera•13mo ago
REST Client - Visual Studio Marketplace
Extension for Visual Studio Code - REST Client for Visual Studio Code
Draggo
DraggoOP•13mo ago
yeah
tera
tera•13mo ago
paste full .http file you use -> $code
MODiX
MODiX•13mo ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
Draggo
DraggoOP•13mo ago
@WebApiHost = http://localhost:5555

GET {{WebApiHost}}/

###

GET {{WebApiHost}}/items

###

POST {{WebApiHost}}/items
Content-Type: application/json

{
"Name" : "Example item 3",
"Description": "Description 3",
"Price": 25.50,
"Quantity": 30
}

###
GET {{WebApiHost}}/items/1

###

PUT {{WebApiHost}}/items/1
Content-Type: application/json

{
"itemId" : 1,
"Name" : "Example item 1",
"Description": "Description 1",
"Price": 25.50,
"Quantity": 30
}

###

DELETE {{WebApiHost}}/items/1
@WebApiHost = http://localhost:5555

GET {{WebApiHost}}/

###

GET {{WebApiHost}}/items

###

POST {{WebApiHost}}/items
Content-Type: application/json

{
"Name" : "Example item 3",
"Description": "Description 3",
"Price": 25.50,
"Quantity": 30
}

###
GET {{WebApiHost}}/items/1

###

PUT {{WebApiHost}}/items/1
Content-Type: application/json

{
"itemId" : 1,
"Name" : "Example item 1",
"Description": "Description 1",
"Price": 25.50,
"Quantity": 30
}

###

DELETE {{WebApiHost}}/items/1
my put message is not found
Draggo
DraggoOP•13mo ago
No description
tera
tera•13mo ago
from this?
Draggo
DraggoOP•13mo ago
Whenever I send a new request like I was doing before not from that
tera
tera•13mo ago
ok thats another issue
Draggo
DraggoOP•13mo ago
ok
tera
tera•13mo ago
you click here to run that put request?
No description
Draggo
DraggoOP•13mo ago
yes!
tera
tera•13mo ago
strange it works fine for me
Draggo
DraggoOP•13mo ago
oh wait
tera
tera•13mo ago
try restart vscode šŸ˜„
Draggo
DraggoOP•13mo ago
now its happening on the first get too ok 1 sec
Draggo
DraggoOP•13mo ago
still happening
No description
Draggo
DraggoOP•13mo ago
this from first get second get works
tera
tera•13mo ago
ok but let's fix method not allowed issue first
Draggo
DraggoOP•13mo ago
kk
tera
tera•13mo ago
you still get method not allowed on put?
Draggo
DraggoOP•13mo ago
204 no content now
tera
tera•13mo ago
ok that means its fixed and delete?
Draggo
DraggoOP•13mo ago
same thing
tera
tera•13mo ago
ok which endpoint is 404 not found //app.MapGet("/items/{id}", async (int id, InventoryDbContext dbContext) => // await dbContext.Items.FindAsync(id) ?? Results.NotFound()); this?
Draggo
DraggoOP•13mo ago
I think so?
tera
tera•13mo ago
well do you have item in the database that you try to get? do post and then try get also... dont ever use in memory with ef core 😬
Draggo
DraggoOP•13mo ago
dbContext.Items.AddRange(
new Item { Name = "Example Item 1", Description = "Description 1", Price = 10, Quantity = 100 },
new Item {
Price = 20, Quantity = 50 }
dbContext.Items.AddRange(
new Item { Name = "Example Item 1", Description = "Description 1", Price = 10, Quantity = 100 },
new Item {
Price = 20, Quantity = 50 }
is that going to be an issue?
tera
tera•13mo ago
In-memory Database Provider - EF Core
Information on the Entity Framework Core in-memory database provider
tera
tera•13mo ago
it even says on the side
No description
Draggo
DraggoOP•13mo ago
its for a school project, It won be for production
tera
tera•13mo ago
add Id = something.. because probably in memory doesn't automatically assign Id
Draggo
DraggoOP•13mo ago
oh really ok one sec
tera
tera•13mo ago
i mean even for development... its more pain in the ass than worth. it's really easy to use something like sqlite provider even
Draggo
DraggoOP•13mo ago
Same issue
tera
tera•13mo ago
what did you set Id to? šŸ˜„
Draggo
DraggoOP•13mo ago
1 and 2
tera
tera•13mo ago
and what is your get request GET {{WebApiHost}}/items/1 ?
Draggo
DraggoOP•13mo ago
Method not allowed 405
tera
tera•13mo ago
wtf...
Draggo
DraggoOP•13mo ago
😭 I really appreciate you trying to help me btw
tera
tera•13mo ago
try this
Invoke-WebRequest -Uri "http://localhost:5555/items/1"
Invoke-WebRequest -Uri "http://localhost:5555/items/1"
Draggo
DraggoOP•13mo ago
No description
tera
tera•13mo ago
can you post your program.cs again in $code pls
MODiX
MODiX•13mo ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
Draggo
DraggoOP•13mo ago
using InventoryPro.Database;
using Microsoft.EntityFrameworkCore;



var builder = WebApplication.CreateBuilder(args);


builder.Services.AddDbContext<InventoryDbContext>(options =>
options.UseInMemoryDatabase("InventoryDatabase"));

var app = builder.Build();
app.Urls.Add("http://localhost:5555");

app.UseHttpsRedirection();



using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<InventoryDbContext>();
if (!dbContext.Items.Any())
{
dbContext.Items.AddRange(
new Item { ItemId = 1, Name = "Example Item 1", Description = "Description 1", Price = 10, Quantity = 100 },
new Item { ItemId = 2, Name = "Example Item 2", Description = "Description 2", Price = 20, Quantity = 50 }
);
dbContext.SaveChanges();
}
}
app.MapGet("/items", async (InventoryDbContext dbContext) =>
await dbContext.Items.ToListAsync());


//app.MapGet("/items/{id}", async (int id, InventoryDbContext dbContext) =>
// await dbContext.Items.FindAsync(id) ?? Results.NotFound());


app.MapPost("/items", async (Item newItem, InventoryDbContext dbContext) =>
{
dbContext.Items.Add(newItem);
await dbContext.SaveChangesAsync();
return Results.Created($"/items/{newItem.ItemId}", newItem);
});


app.MapPut("/items/{itemId}", async (int itemId, Item updatedItem, InventoryDbContext dbContext) =>
{
var item = await dbContext.Items.FindAsync(itemId);
if (item == null) return Results.NotFound();

item.Name = updatedItem.Name;
item.Description = updatedItem.Description;
item.Price = updatedItem.Price;
item.Quantity = updatedItem.Quantity;
await dbContext.SaveChangesAsync();
return Results.NoContent();
});

app.MapDelete("/items/{id}", async (int id, InventoryDbContext dbContext) =>
{
var item = await dbContext.Items.FindAsync(id);
if (item == null) return Results.NotFound();

dbContext.Items.Remove(item);
await dbContext.SaveChangesAsync();
return Results.NoContent();
});

app.Run();
using InventoryPro.Database;
using Microsoft.EntityFrameworkCore;



var builder = WebApplication.CreateBuilder(args);


builder.Services.AddDbContext<InventoryDbContext>(options =>
options.UseInMemoryDatabase("InventoryDatabase"));

var app = builder.Build();
app.Urls.Add("http://localhost:5555");

app.UseHttpsRedirection();



using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<InventoryDbContext>();
if (!dbContext.Items.Any())
{
dbContext.Items.AddRange(
new Item { ItemId = 1, Name = "Example Item 1", Description = "Description 1", Price = 10, Quantity = 100 },
new Item { ItemId = 2, Name = "Example Item 2", Description = "Description 2", Price = 20, Quantity = 50 }
);
dbContext.SaveChanges();
}
}
app.MapGet("/items", async (InventoryDbContext dbContext) =>
await dbContext.Items.ToListAsync());


//app.MapGet("/items/{id}", async (int id, InventoryDbContext dbContext) =>
// await dbContext.Items.FindAsync(id) ?? Results.NotFound());


app.MapPost("/items", async (Item newItem, InventoryDbContext dbContext) =>
{
dbContext.Items.Add(newItem);
await dbContext.SaveChangesAsync();
return Results.Created($"/items/{newItem.ItemId}", newItem);
});


app.MapPut("/items/{itemId}", async (int itemId, Item updatedItem, InventoryDbContext dbContext) =>
{
var item = await dbContext.Items.FindAsync(itemId);
if (item == null) return Results.NotFound();

item.Name = updatedItem.Name;
item.Description = updatedItem.Description;
item.Price = updatedItem.Price;
item.Quantity = updatedItem.Quantity;
await dbContext.SaveChangesAsync();
return Results.NoContent();
});

app.MapDelete("/items/{id}", async (int id, InventoryDbContext dbContext) =>
{
var item = await dbContext.Items.FindAsync(id);
if (item == null) return Results.NotFound();

dbContext.Items.Remove(item);
await dbContext.SaveChangesAsync();
return Results.NoContent();
});

app.Run();
tera
tera•13mo ago
but.. its commented šŸ˜„
//app.MapGet("/items/{id}", async (int id, InventoryDbContext dbContext) =>
// await dbContext.Items.FindAsync(id) ?? Results.NotFound());
//app.MapGet("/items/{id}", async (int id, InventoryDbContext dbContext) =>
// await dbContext.Items.FindAsync(id) ?? Results.NotFound());
no wonder it doesnt work
Draggo
DraggoOP•13mo ago
Operator '??' cannot be applied to operands of type 'Item' and 'IResult'CS0019 If i uncomment it
tera
tera•13mo ago
ok 2 things dont use FindAsync.. use FirstOrDefaultAsync(x => x.Id == id) and then do something like
=> {
item = await dbContext.Items.FirstOrDefaultAsync(x => x.Id == id)
if (item is null)
return Results.NotFound()

return Results.Ok(item)
}
=> {
item = await dbContext.Items.FirstOrDefaultAsync(x => x.Id == id)
if (item is null)
return Results.NotFound()

return Results.Ok(item)
}
if you can see the argument for FindAsync is.. object. its not type safe. it's extra easy to shoot yourself in the foot and send something you dont intend
Draggo
DraggoOP•13mo ago
app.MapGet("/items/{id}", async (int id, InventoryDbContext dbContext)=> { item = await dbContext.Items.FirstOrDefaultAsync(x => x.Id == id) if (item is null) return Results.NotFound()
return Results.Ok(item) } like this?
app.MapGet("/items/{id}", async (int id, InventoryDbContext dbContext)=> {
item = await dbContext.Items.FirstOrDefaultAsync(x => x.Id == id)
if (item is null)
return Results.NotFound()

return Results.Ok(item)
}
app.MapGet("/items/{id}", async (int id, InventoryDbContext dbContext)=> {
item = await dbContext.Items.FirstOrDefaultAsync(x => x.Id == id)
if (item is null)
return Results.NotFound()

return Results.Ok(item)
}
tera
tera•13mo ago
yes
Draggo
DraggoOP•13mo ago
No description
tera
tera•13mo ago
; ? šŸ˜„ also instead x.Id neets to be x.ItemId per your model hover with mouse it should hint you errors
Draggo
DraggoOP•13mo ago
No description
tera
tera•13mo ago
whats the error it says
Draggo
DraggoOP•13mo ago
mapget takes 3 arguments
tera
tera•13mo ago
can you copy or full screenshot of this its cut off
Draggo
DraggoOP•13mo ago
No description
tera
tera•13mo ago
you are missing ) at the end look at MapPost below
Draggo
DraggoOP•13mo ago
No description
Draggo
DraggoOP•13mo ago
Item does not exist in current context
tera
tera•13mo ago
šŸ˜„ well duh. you didnt declare it anywhere var item =...
Draggo
DraggoOP•13mo ago
ok yay! it works now we are back at 204 not found on put and delete 204 no content ssorry
tera
tera•13mo ago
but?? thats OK did you write this code yourself or..?
Draggo
DraggoOP•13mo ago
no it was a team member, they were having trouble debugging it
tera
tera•13mo ago
you return NoContent here.. which is 204
No description
tera
tera•13mo ago
so that means it executed all the way
Draggo
DraggoOP•13mo ago
ahhh so its working gotcha! sorry lol
tera
tera•13mo ago
yes šŸ˜„
Draggo
DraggoOP•13mo ago
What was the root issue (simplified lol)
tera
tera•13mo ago
well for method not allowed.. i dont know. you werent executing the requests right.. since the commands you ran in terminal worked ok i dont use this vscode extension so idk if there are some gotchas.. or something to be aware of i recommend you learn to use some tool like postman/insomnia/other... it might help usually compare what we changed... šŸ™‚ it should tell you what were the issues
Draggo
DraggoOP•13mo ago
ā¤ļø

Did you find this page helpful?