ASP.net Web API的ActionFilterAttribute抛出InvalidOperationException:Sequence包含多个元素

时间:2013-12-23 09:39:04

标签: asp.net asp.net-mvc asp.net-web-api asp.net-mvc-5

在我们的生产环境中,有些用户无法通过我们的Web API登录,因为服务器端会抛出以下异常:

System.InvalidOperationException: Sequence contains more than one element
   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__1.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 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.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 System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>d__1.MoveNext()

我无法弄清楚如何在开发环境中重现这一点。错误消息也很不清楚,我们的代码在堆栈跟踪中没有任何内容。

你们有没有遇到过这个问题?什么可能导致它?

2 个答案:

答案 0 :(得分:3)

花了半天时间,找到了原因,在owin appbuilder链中app.UseOAuthBearerTokens(OAuthOptions);被调用了两次。这导致两个类似的AuthenticationResults导致一个Sequence包含多个元素。

答案 1 :(得分:-3)

如果集合中不包含0或1个元素并且您使用的是.SingleOrDefault(),则会发生此错误。

请改用.FirstOrDefault()