GET <url> net :: ERR_CONNECTION_RESET

时间:2017-07-13 13:32:17

标签: c# asp.net .net asp.net-web-api

我有返回JSON的WebAPI控制器。代码如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using GetWork.Data;
using GetWork.Models.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Cors;

namespace GetWork.Controllers.Api
{
    [Produces("application/json")]
    [EnableCors("SiteCorsPolicy")]
    public class ConversationsApiController : Controller
    {
        private readonly ApplicationDbContext _context;

        public ConversationsApiController(ApplicationDbContext context)
        {
            _context = context;
        }
        //This one works fine
        // GET: api/Conversations/5
        [HttpGet]
        [Route("api/conversations/getconversations/{id}")]
        public List<Conversation> GetConversations(int id)
        {
            var conversations = _context.Conversations.Include(o => o.Offerer).Where(c => c.JobRelated.ID == id).ToList();

            return conversations ?? new List<Conversation>();
        }
        //This one works fine
        [HttpGet]
        [Route("api/conversations/getmyoffers/{userId}")]
        public List<Job> GetMyOffers(string userId)
        {
            return _context.Job.Include(c => c.Conversations).ToList();

        }

    }
}

调用GetMyOffers方法时,在浏览器中我可以看到这样的错误:

GET http://localhost:8377/api/conversations/getMyOffers/70a741c2-b847-4063-ab94-7f2e93860ab6 net::ERR_CONNECTION_RESET

但是当我对数据进行硬编码(省略_context)时,一切正常。其他方法正在发挥作用。

导致此类问题的原因是什么?

更新

最后,我发现了这样的期望:

Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'job' with type 'GetWork.Models.Domain.Job'

需要验证我的模型。

SOLUTION:

默认情况下,序列化程序无法处理自引用循环。我已将以下行放到配置中:

options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

它在序列化期间忽略所有循环引用。它对我有用,但我知道它的解决方法而不是解决方法。 (考虑使用DTO而不是纯模型)。

1 个答案:

答案 0 :(得分:0)

如果在删除_context并且只返回硬编码数据时它有效,我会怀疑它很可能是超时:

可以通过增加请求超时来修复,例如:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
   <system.webServer>
             ....
        <aspNetCore requestTimeout="00:20:00"  .... />
    </system.webServer>
</configuration>

您可以通过包装_context.Job.Include(c => c.Conversations).ToList();来提高代码的健壮性 在try catch块中,当抛出异常时返回有意义的东西,例如

try {
   return _context.Job.Include(c => c.Conversations).ToList();
}
catch(Exception ex) {
   return something meaningful here...
}