【发布时间】:2021-12-15 20:33:05
【问题描述】:
我的 Web API 应用程序正在运行,我可以使用主键进行 GET,但我需要能够使用其他字段(例如 Widgetname)进行 GET,并且我知道我需要指定 '[Route("api/[controller ]/[action]")]' 才能正常工作。 “GetByID”操作有效,但“GetByName”操作无效。我将我正在做的实际工作的名称更改为“Widget”,所以我可能没有正确重命名所有内容。代码可以编译,但是当我尝试对“GetByName”进行 API 调用时,出现 404 错误。这是我的代码:
namespace WidgetAPI.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class WidgetStuffController : ControllerBase
{
private readonly WidgetDbContext _context;
public WidgetStuffController(WidgetDbContext context)
{
_context = context;
}
// GET: api/WidgetStuff
[HttpGet]
public async Task<ActionResult<IEnumerable<WidgetStuff>>> GetWidgetStuff()
{
return await _context.StuffHosts.ToListAsync();
}
// GET: api/WidgetStuff/GetByID
[HttpGet("{ID}"), ActionName("GetByID")]
public async Task<ActionResult<WidgetStuff>> GetByUUID(string ID)
{
var widgetStuff = await _context.StuffHosts.FindAsync(ID);
if (widgetStuff == null)
{
return NotFound();
}
return widgetStuff;
}
// GET: api/WidgetStuff/GetByName
[HttpGet("{Name}"), ActionName("GetByName")]
public async Task<ActionResult<WidgetStuff>> GetByName(string Name)
{
var widgetStuff = await _context.StuffHosts.FindAsync(Name);
if (widgetStuff == null)
{
return NotFound();
}
return widgetStuff;
}
}
}
如果您需要查看我的 DBContext 或模型,请告诉我。
【问题讨论】:
-
请发布您用于 GetByName 和 GetById 的完整网址
-
网址:
https://localhost:<port>/api/WidgetStuff/GetByID/<ID>https://localhost:<port>/api/WidgetStuff/GetByName/<Name> -
尝试调试 - 此代码应该可以工作
if (widgetStuff == null) { return NotFound(); }您可能在数据库中找不到任何密钥,因此返回 404。
标签: c# asp.net-core-mvc