JsonResult没有返回大量的项目并抛出错误?

时间:2013-05-24 11:03:33

标签: asp.net json asp.net-mvc-3

我使用asp.net mvc,控制器和存储库看起来工作正常。

这是存储库:

public IEnumerable<ReadingListMediaChannel> GetReadingListsById(int readingListId)
        {
            try
            {
                var x = NeptuneUnitOfWork.ReadingList.FindByID(readingListId).ReadingListMediaChannels.ToList();
                return x;
            }
            catch (Exception ex)
            {
                Logger.Error("GetReadingLists - failed to retrieve reading lists.", ex);
                throw;
            }
        }

当计算完成并且我试图返回2067个对象的JsonResult但是我得到以下异常:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.


[ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.]
   System.Data.Objects.ObjectContext.EnsureConnection() +11448512
   System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +66
   System.Data.Objects.DataClasses.EntityReference`1.Load(MergeOption mergeOption) +229
   System.Data.Objects.DataClasses.RelatedEnd.DeferredLoad() +497
   System.Data.Objects.Internal.LazyLoadBehavior.LoadProperty(TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject) +157
   System.Data.Objects.Internal.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item) +149
   System.Data.Entity.DynamicProxies.ReadingListMediaChan_AA75ADD44097B0AF40DBB84D6E509EE9D2EA11F705268633DBD1D4743DEEA37B.get_MediaChannel() +151

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +229
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +193
   System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +35
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +733
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +1968
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +166
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +195
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +1923
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +166
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat) +114
   System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context) +282
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +33
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +726368
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +265
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +726324
   System.Web.Mvc.Controller.ExecuteCore() +159
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +334
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +15
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +52
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

2 个答案:

答案 0 :(得分:3)

堆栈跟踪中的以下行:

System.Data.Objects.Internal.LazyLoadBehavior.LoadProperty(

表示问题与访问延迟加载的属性有关,然后在会话关闭后进行访问。

答案 1 :(得分:0)

而不是返回使用慢速JavascriptSerializer的JsonResult,而是直接使用其他一些序列化程序和序列化程序来响应Response.OutputStream。

在当前样本中使用Newtonsoft.Json

public void Test()
{
    var sampleData = new {foo = "bar"};

    var serializer = new JsonSerializer();

    Response.ContentType = "application/json";
    using (var textWriter = new StreamWriter(Response.OutputStream))
    {
        serializer.Serialize(textWriter, sampleData);
    }
}