C# 中的 HttpPut 请求
HttpPut Request in C#
我对这个 Web API 东西还很陌生,我正在尝试在我的计算机上设置对本地数据库的简单 http 请求。我有一个看起来像这样的获取请求:
[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);
}
这只是 returns 数据库中的所有项目或与指定 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()
方法时,新项目不存在。
您需要在new ListTable()
之后设置属性。类似于 new ListTable() { Title = title, ... }
您将需要新建一个实体实例以添加 [ListTable
],然后将其添加到您的数据库上下文(假设它是 db
,基于您的 GET
示例. 一旦你将它添加到上下文中,那么你 .SaveChanges()
- 我假设你的 ListTable
实体有名为 Title
和 Description
的列(将这些行更改为你拥有的任何内容他们被命名为):
ListTable listTableToAdd = new ListTable()
{
Title = title,
Description = descr
}
db.ListTables.Add(listTableToAdd);
db.SaveChanges();
我对这个 Web API 东西还很陌生,我正在尝试在我的计算机上设置对本地数据库的简单 http 请求。我有一个看起来像这样的获取请求:
[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);
}
这只是 returns 数据库中的所有项目或与指定 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()
方法时,新项目不存在。
您需要在new ListTable()
之后设置属性。类似于 new ListTable() { Title = title, ... }
您将需要新建一个实体实例以添加 [ListTable
],然后将其添加到您的数据库上下文(假设它是 db
,基于您的 GET
示例. 一旦你将它添加到上下文中,那么你 .SaveChanges()
- 我假设你的 ListTable
实体有名为 Title
和 Description
的列(将这些行更改为你拥有的任何内容他们被命名为):
ListTable listTableToAdd = new ListTable()
{
Title = title,
Description = descr
}
db.ListTables.Add(listTableToAdd);
db.SaveChanges();