ASP Core:ApiController.ExecuteAsync中的NullReferenceException

时间:2016-11-07 11:52:39

标签: c# asp.net-core asp.net-core-mvc asp.net-core-webapi

我使用带有WebAPI模板的ASP.NET核心应用程序,并且所有现有控制器都继承自System.Web.Http.ApiController
因此,请求以方法ExecuteAsync中指向NRE的错误结束。此异常的堆栈大小如下所示:

System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionFilterAsync>d__28.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.<Invoke>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1.<RequestProcessingAsync>d__2.MoveNext()

有趣的时刻我发现覆盖ExecuteAsync方法:controllerContext.ControllerDescriptor属性具有空值(null)并且ExecuteAsync的基本实现会抛出此异常,尝试执行代码

ServicesContainer services = controllerContext.ControllerDescriptor.Configuration.Services;

Controller state

另一个有用的时刻是调试日志消息:

Microsoft.AspNetCore.Mvc.Internal.ActionSelector: Debug: Action 'WebAPI.Controllers.AuthController.Post (WebAPI)' with id '9848905d-176e-44bc-9453-53c5185b46c6' did not match the constraint

完整的调试消息堆栈如下所示:

Microsoft.AspNetCore.Hosting.Internal.WebHost: Information: Request starting HTTP/1.1 GET http://localhost:64513/api/auth application/json; charset=utf-8 0
Microsoft.AspNetCore.Routing.Tree.TreeRouter: Debug: Request successfully matched the route with name '' and template 'api/auth'.
Microsoft.AspNetCore.Mvc.Internal.ActionSelector: Debug: Action 'WebAPI.Controllers.AuthController.Post (WebAPI)' with id '9848905d-176e-44bc-9453-53c5185b46c6' did not match the constraint 'Microsoft.AspNetCore.Mvc.Internal.HttpMethodActionConstraint'
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker: Debug: Executing action WebAPI.Controllers.AuthController.ExecuteAsync (WebAPI)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker: Information: Executing action method WebAPI.Controllers.AuthController.ExecuteAsync (WebAPI) with arguments (System.Web.Http.Controllers.HttpControllerContext, System.Threading.CancellationToken) - ModelState is Valid
Exception thrown: 'System.NullReferenceException' in System.Web.Http.dll
Exception thrown: 'System.NullReferenceException' in Microsoft.AspNetCore.Mvc.Core.dll
Exception thrown: 'System.NullReferenceException' in mscorlib.dll
Exception thrown: 'System.NullReferenceException' in mscorlib.dll
Exception thrown: 'System.NullReferenceException' in mscorlib.dll
Exception thrown: 'System.NullReferenceException' in mscorlib.dll
Microsoft.AspNetCore.Server.Kestrel: Error: Connection id "0HL06UADGPFB4": An unhandled exception was thrown by the application.

Controller的操作标有AspNetCore.Mvc HTTP方法属性,但在以下情况下对应用程序来说不是问题:

using BodyObject = Microsoft.AspNetCore.Mvc.FromBodyAttribute;
using OPTIONS = Microsoft.AspNetCore.Mvc.HttpOptionsAttribute;
using POST = Microsoft.AspNetCore.Mvc.HttpPostAttribute;
[OPTIONS, POST]
public async Task<PostResponse> Post([BodyObject] PostRequest model)

我很困惑这个问题的真正根源是什么。有没有人有任何想法?

//我认为,为了更好地理解这个问题,必须在那里展示另外一些代码:

project.json依赖项

  "dependencies": {
    "Microsoft.AspNet.WebApi.Core": "5.2.3",
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.AspNetCore.Routing": "1.0.0"
  },

Startup.RegisterServices

services.AddMvc(options => { /* some filters add code */ });
services.AddRouting();

Startup.Configure

#if DEBUG
loggerFactory.AddDebug((a, b) => true);
#endif
app.UseMvc();
app.UseCors(builder => builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod());

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

1 个答案:

答案 0 :(得分:1)

好的,感谢 Pranav 的回复。 出于某种原因,MVC / WebAPI控制器的alpha版本混合运行良好。但生活是一件复杂的事情,并且存在与ControllerApiController不兼容相关的问题。唯一的解决方案是删除所有AspCore.WebApi关系并安装Microsoft.AspNetCore.Mvc.WebApiCompatShim包。