为什么我得到System.NullReferenceException:对象引用未设置为对象的实例

Why im getting System.NullReferenceException: Object reference not set to an instance of an object

提问人:UntitledUserForEach 提问时间:5/31/2022 更新时间:5/31/2022 访问量:2844

问:

有人可以向我解释这个例外吗?我在用户控制器中有这个方法

[HttpGet("{username}/plays")]
public async Task<ActionResult<int>> GetUserPlays(string username)
{
    return Ok(await _unitOfWork.TrackRepository.CountPlays(username));
} 

如果不进入 TrackRepository 方法,它会抛出异常:

2022-05-31 14:37:02.8644|0|ERROR|gspark.Middleware.ExceptionMiddleware|Object reference not set to an instance of an object. System.NullReferenceException: Object reference not set to an instance of an object.
   at gspark.Controllers.UsersController.GetUserPlays(String username) in C:\Users\GSpark\source\repos\gspark\gspark\Controllers\UsersController.cs:line 119
   at lambda_method202(Closure , Object )
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)

TrackRepository 方法:

public async Task<int> CountPlays(string username)
{
    return await _context.Tracks
       .Include(t => t.User)
       .Where(t => t.User.UserName == username)
       .SumAsync(t => t.Plays);
}

是关于映射的吗?或者,如果是存储库方法导致问题,如果是这样,为什么调试不要进入此方法?在何处以及为何引发此异常?

asp.net nullreferenceexception

评论

0赞 derpirscher 5/31/2022
这回答了你的问题吗?什么是 NullReferenceException,如何修复它?

答:

2赞 JDandChips 5/31/2022 #1

如果你没有达到,那么这将表明要么是 或 是 .CountPlays_unitOfWorkTrackRepositorynull

若要阐明这一点,请插入断点并检查调试器中的值。或者,如果你不能这样做,那么我建议你使用类似于以下内容的if语句:

if (_unitOfWork == null || _unitOfWork.TrackRepository == null) 
{
    return new Exception("Ooops");
}

如果还是没有喜悦,那就分享初始化对象的代码_unitOfWork

评论

0赞 UntitledUserForEach 5/31/2022
哦,天哪,我忘了在我的 UnitOfWork 类中设置 Repository。谢谢你指出这一点