我正在尝试在 ASP.NET Core Web API 中发出
HttpGet
请求。
问题是我不知道如何用查询来发出get请求。
这是我的模型:
public class Predoslepozicie
{
[Key]
public int Id { get; set; }
[Required]
public int idZamestnanca { get; set; }
[Required]
public string Pozicia { get; set; }
[Required]
public DateTime DatumUkoncenia { get; set; }
[Required]
public DateTime DatumNastupu { get; set; }
}
控制器
// GET: api/Predoslepozicie/5
[HttpGet("{idZamestnanca}")]
public async Task<ActionResult<Predoslepozicie>> GetPredoslepozicie(int idZamestnanca)
{
var Predoslepozicie = await _context.Predoslepozicie.FindAsync(idZamestnanca);
if (Predoslepozicie == null)
{
return NotFound();
}
return Predoslepozicie;
}
idZamestnanca
是SQL数据库中另一个表的id,我需要选择所有行where id = x
。
例如
idZamestnanca = 9
在表中出现 10 次,我需要查询仅返回这 10 行。
当我尝试使用
idZamestnanca
发出请求时,我收到状态 404。
当我尝试使用 idZamestnanca 发出请求时,我收到状态 404。
您现在收到的 404 消息可能有两个主要原因。
当控制器命中但返回 404 时:
假设这是您的桌子。您想从此表中按
idZamestnanca
进行搜索。这里 PrimaryKey
是 Id
。但如果您想通过 idZamestnanca
进行搜索,那么 FindAsync(idZamestnanca)
将不起作用。因为 FindAsync
找到具有给定主键值的实体,所以 FindAsync
将始终返回 404.on
您的场景的解决方案:
您应该使用以下代码来执行查询:
var Predoslepozicie = _context.Predoslepozicies.Where(id=>id.idZamestnanca == idZamestnanca).ToList();
注意: 当您替换上面的查询时,它会对您大喊大叫。
因为这是一个
List
但你在这里定义了一个对象 Task<ActionResult<Predoslepozicie>>
。
最终修复:
替换
Task<ActionResult<List<Predoslepozicie>>>
,这样你的控制器操作应该如下所示:
[HttpGet("{idZamestnanca}")]
public async Task<ActionResult<List<Predoslepozicie>>> GetPredoslepozicie(int idZamestnanca)
{
var Predoslepozicie = _context.Predoslepozicies.Where(id => id.idZamestnanca == idZamestnanca).ToList();
if (Predoslepozicie == null)
{
return NotFound();
}
return Predoslepozicie;
}
或者你可以简单地像下面这样做:
良好实践:
[Route("api/[controller]")]
[ApiController]
public class FrodoNicitelController : ControllerBase
{
private readonly ApplicationDbContext _context;
public FrodoNicitelController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet("{idZamestnanca}")]
public async Task<ActionResult> GetPredoslepozicie(int idZamestnanca)
{
var Predoslepozicie = _context.Predoslepozicies.Where(id => id.idZamestnanca == idZamestnanca).ToList();
if (Predoslepozicie == null)
{
return NotFound();
}
return Ok(Predoslepozicie);
}
}
输出:
当控制器未命中并返回 404 时:
在这种情况下,您没有正确发送您的属性路由。当您将路由属性设置为
[HttpGet("{idZamestnanca}")]
时,在这种情况下您必须像下面这样调用您的API URL:
https://localhost:7132/api/YourControllerName/101 // Need to call like this
注意: 请记住,在这里您必须直接在
controller
之后传递参数,然后是 /
backslash
,而不是通过 ?
或如下所示:
https://localhost:7132/api/YourControllerName?idZamestnanca=1 // Not like this