c# - 未使用属性调用 HttpGet 方法
问题描述
该GetItems
方法工作正常GetItem
,但属性“id”不是。当我发送 GET 请求时,我得到了所有返回的项目,这意味着GetItems()
被调用。我错过了什么?
// GET request: https://localhost:xxxxx/api/Items
// Working
[HttpGet]
public async Task<ActionResult<IEnumerable<Item>>> GetItems()
{
return await _context.items.ToListAsync();
}
// GET request: https://localhost:xxxxx/api/Items/2
// Not running
[HttpGet("{id}")]
public async Task<ActionResult<Item>> GetItem(long id)
{
var item = await _context.items.FindAsync(id);
if (item == null)
{
return NotFound();
}
return item;
}
我想过滤带有名称的项目,但这与上面的 GetItem(long id) 有相同的问题,所有项目都被返回。
GET request: https://localhost:xxxxx/api/Items?name=aaa
// Not running
[HttpGet("{name}")]
public async Task<ActionResult<IEnumerable<Item>>> GetItems(string name)
{
var item = await _context.items.Where(x => x.Name == name).ToListAsync();
if (item == null)
{
return NotFound();
}
return item;
}
[HttpPost]
public async Task<ActionResult<TodoItem>> PostTodoItem(TodoItem todoItem)
{
_context.TodoItems.Add(todoItem);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetTodoItemById), new { id = todoItem.Id }, todoItem);
}
响应示例:
{
"id": 1,
"name": "aaa",
"isRegistered": true
}
{
"id": 2,
"name": "aaa",
"isRegistered": false
}
{
"id": 3,
"name": "bbb",
"isRegistered": false
}
在 Startup.cs 中配置方法:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
解决方案
您可以像这样添加Action
到您的Route
:[Route("api/[controller]/[action]")]
,下面是一个工作演示:
[Route("api/[controller]/[action]")]
[ApiController]
public class ItemsController : ControllerBase
{
//...
[HttpGet]
public async Task<ActionResult<IEnumerable<Item>>> GetItems()
{
return await _context.Items.ToListAsync();
}
[HttpGet]
public async Task<ActionResult<Item>> GetItemById(int id)
{
var item = await _context.Items.FindAsync(id);
if (item == null)
{
return NotFound();
}
return item;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Item>>> GetItemByName(string name)
{
var item = await _context.Items.Where(x => x.Name == name).ToListAsync();
if (item == null)
{
return NotFound();
}
return item;
}
}
获取请求:
1:https://localhost:xxxxx/api/Items/getitems
2:https://localhost:xxxxx/api/Items/GetItemById?id=xx
3:https://localhost:xxxxx/api/Items/GetItemByName?name=xx
发帖请求:
https://localhost:xxxxx/api/Items/todoitem
结果:
推荐阅读
- python - 3D t-sne 的特定标记
- node.js - 推送被拒绝,在 heroku 上部署 nodejs 应用程序时无法编译 Node.js 应用程序
- netsuite - 以编程方式安排地图缩减脚本
- python - Pygame 窗口不会出现在 Jupyter 中
- angular - Angular 从多个 http 服务获取数据并映射它们
- excel - 为什么将我的数组读入 VBA 中的单元格时,它会重复每一行?
- python - 如何判断列表中的项目何时在 Python 中更改了位置
- java - 每个新会话都需要 dbms_java.grant_permission
- pdf - 包含 Unicode 字符(跨越两个字节)的 PDF 注释未在 Firefox 中显示,但在 chrome 中工作正常
- python - 如何使用kivy每分钟调用一个函数?