我的api方法有问题。我有一个方法GetDrones不能正常工作(这里没有足够的逻辑。我只是把它做得尽可能短以使其更简单)[方式0]:
[Produces("application/json")]
[Route("api/[controller]")]
public class OwnersController : Controller
{
private readonly ApplicationDbContext _context;
private readonly ClaimsPrincipal _caller;
public OwnersController(ApplicationDbContext context, IHttpContextAccessor httpContextAccessor)
{
_context = context;
_caller = httpContextAccessor.HttpContext.User;
}
[HttpGet("GetOwnersDrones")]
public List<Drone> GetDrones()
{
var userId = _caller.Claims.Single(c => c.Type == "id");
var customer = _context.Customers.Single(c => c.Identity.Id == userId.Value);
var owner = _context.Owners.Single(o => o.CustomerId == customer.Id);
return _context.Drones.ToList();
}
}
[HttpGet("GetOwnersDrones")]
public List<Drone> GetDrones()
{
var userId = _caller.Claims.Single(c => c.Type == "id");
var customer = _context.Customers.Single(c => c.Identity.Id == userId.Value);
var owner = _context.Owners.Single(o => o.CustomerId == customer.Id);
return null;
}
[HttpGet("GetOwnersDrones")]
public List<Drone> GetDrones()
{
var userId = _caller.Claims.Single(c => c.Type == "id");
var customer = _context.Customers.Single(c => c.Identity.Id == userId.Value);
//var owner = _context.Owners.Single(o => o.CustomerId == customer.Id);
return _context.Drones.ToList();
}
_context.Drones.ToList();
和
_context.Owners.Single(o => o.CustomerId == customer.Id);
在一种方法中不起作用?我该如何解决并使原始方法起作用?
更新
[HttpGet("GetOwnersDrones")]
public Owner GetOwnersDrones()
{
var userId = _caller.Claims.Single(c => c.Type == "id");
var customer = _context.Customers.Single(c => c.Identity.Id == userId.Value);
var owner = _context.Owners.SingleOrDefault(o => o.CustomerId == customer.Id);
return owner;
}
答案 0 :(得分:0)
这行很可能是
var owner = _context.Owners.Single(o => o.CustomerId == customer.Id);
未找到查询的任何匹配项,并引发了异常。 我建议阅读有关LINQ的 Single 和 SingleOrDefault 方法,以更好地了解其行为。
通过不调试代码(签出Attacking To Process调试Web API服务),您会错过解决问题所需的所有必要信息。
您必须注意控制器中引发的异常。