【发布时间】:2020-01-01 22:15:40
【问题描述】:
我正在为我的游戏编写一个 API,我开始意识到 GET、POST 和 PUT API 方法的数量真的可以加起来。
所以现在,我正在尝试使其更通用,这样我就不必编写单独的方法,如 GetMonsterList、GetTreasureList、GetPlayerInfo 等。
但我不太确定该怎么做。
这是我目前拥有的非泛型 PUT 方法。
// PUT: api/MonsterLists/5
[HttpPut("{id}")]
public async Task<IActionResult> PutMonsterList(string id, MonsterList monsterList)
{
if (id != monsterList.MonsterId)
{
return BadRequest();
}
_context.Entry(monsterList).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MonsterListExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
这是我尝试概述通用方法的尝试:
// PUT: api/AnyLists/5
[HttpPut("{id}")]
public async Task<IActionResult> PutAnyList(string id, AnyList anyList)
{
if (id != anyList.AnyId)
{
return BadRequest();
}
_context.Entry(anyList).State = EntityState.Modified;
return NoContent();
}
我不明白的问题是,如何将模型传递给这样的通用控件?就像我有 MonsterList、TreasureList、PlayerInfo、WeaponList 等的模型。
我怎样才能对所有这些都使用一种通用方法?
我确实在这里找到了一个类似的问题,Generic Web Api controller to support any model,但答案似乎暗示这不是一个好主意。
这可能吗?
谢谢!
【问题讨论】:
-
它会是一个网页游戏还是你只是为你的游戏制作WEB API服务器?
-
如果@Morasiu 的问题的答案是Web API,那么另一种方法是使用工具来搭建重复的位。 dotnet
aspnet-codegenerator工具可以以繁琐的 GET/PUT/POST 作为起点来创建模型和控制器。见mattmillican.com/blog/aspnetcore-controller-scaffolding -
你已经提到的类似问题中的方法没有错,我在我的 web api 项目中使用了相同的方法,它是一个实时节省
-
@LazZiya 请问你是怎么做到的?即使在阅读了我包含的问题链接后,我仍然试图弄清楚。谢谢!
-
@SkyeBoniwell 我会在周末发布一个样本:)
标签: c# asp.net-core entity-framework-core asp.net-core-webapi