如何解决AggregateException?

时间:2019-07-16 08:57:46

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

我的Web-API中出现了这样的AggregateException:

  

{         “ Message”:“发生错误。”,         “ ExceptionMessage”:“发生一个或多个错误。”,         “ ExceptionType”:“ System.AggregateException”,         “ StackTrace”:“位于System.Threading.Tasks.Task.ThrowIfExceptional(Boolean   includeTaskCanceledExceptions)\ r \ n位于   System.Threading.Tasks.Task 1.GetResultCore(Boolean waitCompletionNotification)\r\n at System.Threading.Tasks.Task 1.get_Result()\ r \ n位于   CapstoneAPI.Controllers.LitigantsController.PostLitigantAndImage(LitigantUpdateReq   E:\ SE1166 \ Spring中的诉讼方)   2019 \ SWP \ capstone \ CapstoneAPI \ CapstoneAPI \ Controllers \ LitigantsController.cs:line   207 \ r \ n在lambda_method(Closure,Object,Object [])\ r \ n在   System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor。<> c__DisplayClass10.b__9(Object   实例,Object [] methodParameters)\ r \ n位于   System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object   实例,Object []参数)\ r \ n位于   System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext   controllerContext,IDictionary 2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()", "InnerException": { "Message": "An error has occurred.", "ExceptionMessage": "Unexpected character encountered while parsing value: {. Path '', line 1, position 1.", "ExceptionType": "Newtonsoft.Json.JsonReaderException", "StackTrace": " at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)\r\n at Newtonsoft.Json.JsonTextReader.ReadAsString()\r\n at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)\r\n at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, IFormatterLogger formatterLogger)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, IFormatterLogger formatterLogger)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Net.Http.HttpContentExtensions.<ReadAsAsyncCore>d__0 1.MoveNext()”         }       }

这是我收到错误的函数:

public IHttpActionResult PostLitigantAndImage (LitigantUpdateReq litigant)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:56524");
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            Litigant _litigant = new Litigant
            {
                ID = litigant.LitigantId,
                Name = litigant.Name,
                Nation = litigant.Nation,
                Sex = litigant.Sex,
                Address = litigant.Address,
                DoB = litigant.DoB,
                HomeTown = litigant.HomeTown,
                IdentifyCard = litigant.IdentifyCard,
                PortraitImage = litigant.PortraitImage
            };
            var rcontent = JsonConvert.SerializeObject(_litigant);
            var buffer = System.Text.Encoding.UTF8.GetBytes(rcontent);
            var content = new ByteArrayContent(buffer);
            HttpResponseMessage response1 = client.PostAsync("api/Litigants", content).Result;
            content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
            LitigantImage image = new LitigantImage
            {
                ID = litigant.LitigantImageId,
                Link = litigant.Link,
                LitigantID = litigant.LitigantId
            };
            rcontent = JsonConvert.SerializeObject(image);
            buffer = System.Text.Encoding.UTF8.GetBytes(rcontent);
            content = new ByteArrayContent(buffer);            
            HttpResponseMessage response2 = client.PostAsync("api/LitigantImages", content).Result;
            if(response1.StatusCode.Equals(HttpStatusCode.Created) && response2.StatusCode.Equals(HttpStatusCode.Created))
            {
                return Content(HttpStatusCode.Created, litigant);
            }
            else
            {
                if (!response1.StatusCode.Equals(HttpStatusCode.Created))
                {
                    return Content(response1.StatusCode, "Error in update class Litigant! Error: \n" + response1.Content.ReadAsAsync<string>().Result);
                    //return Content(response1.StatusCode, "Error in update class Litigant!"); 
                }
                else
                {
                    return Content(response2.StatusCode, "Error in update class LitigantImage! Error: \n" + response1.Content.ReadAsAsync<string>().Result);
                    //return Content(response2.StatusCode, "Error in update class LitigantImage!");
                }
            }
        }

那么,如何确定代码中导致错误的位置?此外,解决错误的最佳方法是什么?

*该类调用了另外2个api,但是当我测试api时,它们可以正常运行并且不会出现错误。我认为是在我设置要发布到api的内容的同时,但我不知道解决该问题的方法。

0 个答案:

没有答案