Search code examples
c#asp.netasp.net-web-apiasp.net-routinghttp-put

HttpPut Request in C#


I'm fairly new to this Web API stuff and I'm trying to set up simple http requests to a local database on my computer. I have a get request that looks like this:

[HttpGet]
[Route("")]
[Route("{ID:int}")]
public IQueryable<ListTable> Get(int id = -1)
{
    if(id == -1)
        return db.ListTables;
    else
        return db.ListTables.Where(lt => lt.ID == id);
}

This just returns all items in the database or one item relating to the specified ID. Now I'm trying to make a put request where I can add a new item to the database or edit item related to a certain ID. I was trying something like this:

[HttpPut]
[Route("{ID:int}")]
[Route("{ID:int}/{TITLE:string}")]
[Route("{ID:int}/{TITLE:string}/{DESCRIPTION:string}")]
public ListTable Put(int id = -1, string title = null, string descr = null)
{
    //if ID == -1 add a new item to the DB
    //else add title and description to the item with the specified ID
}

I am a little unsure of how to add a new item to the database and save the changes. I tried something like db.ListTables.Add(new ListTable()) and db.SaveChanges() but those didn't seem to actually save anything because when I called the Get() method again the new item wasn't there.


Solution

  • You will need to new up an instance of the entity to add [ListTable] and then add it to your database context (assuming it's db based on your GET example. Once you add it to the context, then you .SaveChanges() - I'm assuming your ListTable entity has columns called Title and Description (change those lines to whatever you have them named):

    ListTable listTableToAdd = new ListTable() 
    {
        Title = title,
        Description = descr
    }
    db.ListTables.Add(listTableToAdd);
    db.SaveChanges();