修复Web API方法不正确的行为

时间:2019-05-05 10:19:13

标签: c# asp.net entity-framework linq asp.net-web-api

我的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();
    }
}

enter image description here enter image description here
但是,如果我以这种方式[方法1]更改方法:

[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;
}

enter image description here 或以这种方式[方式2]:

[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();
}

enter image description here 两者都在工作(没有错误弹出)。因此,我得出结论

_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;
}

enter image description here

调试
我已经调试了该方法。如您所见,drones列表和owner不为空,但我仍然收到“无法获得任何回复” enter image description here

1 个答案:

答案 0 :(得分:0)

这行很可能是

    var owner = _context.Owners.Single(o => o.CustomerId == customer.Id);

未找到查询的任何匹配项,并引发了异常。 我建议阅读有关LINQ的 Single SingleOrDefault 方法,以更好地了解其行为。

通过不调试代码(签出Attacking To Process调试Web API服务),您会错过解决问题所需的所有必要信息。

您必须注意控制器中引发的异常。