c#中的HttpPut请求

本文关键字:请求 HttpPut 中的 | 更新日期: 2023-09-27 18:05:44

我对这个Web API的东西相当陌生,我试图在我的计算机上设置简单的http请求到本地数据库。我有一个get请求,看起来像这样:

[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);
}

这只返回数据库中的所有项或与指定ID相关的一个项。现在我试图使一个放请求,我可以添加一个新的项目到数据库或编辑项目相关的某个ID。我正在尝试这样做:

[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
}

我有点不确定如何向数据库添加新项目并保存更改。我尝试了db.ListTables.Add(new ListTable())db.SaveChanges()之类的东西,但这些似乎并没有实际保存任何东西,因为当我再次调用Get()方法时,新项目不在那里。

c#中的HttpPut请求

您将需要新建一个实体实例来添加[ListTable],然后将其添加到数据库上下文(假设它是基于GET示例的db)。一旦您将其添加到上下文中,那么您.SaveChanges() -我假设您的ListTable实体有称为TitleDescription的列(将这些行更改为您命名的任何行):

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

需要设置new ListTable()之后的属性。比如new ListTable() { Title = title, ... }