简体   繁体   English

对 ASP.NET MVC 控制器的 Ajax POST 调用给出 net::ERR_CONNECTION_RESET

[英]Ajax POST call to ASP.NET MVC controller giving net::ERR_CONNECTION_RESET

I am at my wits end about this problem.我对这个问题无能为力。 I've created an ASP.NET MVC 5 website that I am developing and running locally.我创建了一个正在本地开发和运行的 ASP.NET MVC 5 网站。 I've enabled SSL on the site.我在网站上启用了 SSL。 I've created a self-signed certificate for the site.我已经为该站点创建了一个自签名证书。 When I make an ajax POST call to a MVC controller:当我对 MVC 控制器进行 ajax POST 调用时:

$.ajax({
    url: "/Shop/AddToCart/" + id,
    contentType: "application/json; charset=utf-8",
    type: "POST",
    accepts: {
        json: "application/json, text/javascript"
    },
    statusCode: {
        200: function(data) {
            $("#successAlert").show();
            $(function () {
                var returnObject = data;
                layoutVM.addProduct(returnObject);
            });
            },
        400: function() {
            $("#errorAlert").show();
            }
    }
});

I get the following error in the JavaScript console in Chrome: "net::ERR_CONNECTION_RESET".我在 Chrome 的 JavaScript 控制台中收到以下错误:“net::ERR_CONNECTION_RESET”。 It doesn't work in any other browser either.它也不适用于任何其他浏览器。

I know this error has something to do with SSL.我知道这个错误与 SSL 有关。 As I said, I've created a valid certificate for this site.正如我所说,我已经为这个站点创建了一个有效的证书。 Unless I'm missing something, my tools (Chrome dev tools, Glimpse, Fiddler) are not telling me anything useful.除非我遗漏了什么,否则我的工具(Chrome 开发工具、Glimpse、Fiddler)并没有告诉我任何有用的信息。

Any ideas?有任何想法吗?

Update (13 March 2015):更新(2015 年 3 月 13 日):

So upon further investigation, I found that the MVC controller action is indeed being called.所以经过进一步调查,我发现确实调用了 MVC 控制器操作。 In that method, I am returning an instance of HttpStatusCodeResult:在该方法中,我返回 HttpStatusCodeResult 的一个实例:

[HttpPost]
public ActionResult AddToCart(int id)
{
    int numChanges = 0;
    var cart = ShoppingCart.GetCart(httpContextBase);
    Data.Product product = null;
    _productRepository = new ProductRepository();

    product = _productRepository.GetProducts()
          .Where(x => x.ProductID == Convert.ToInt32(id)).FirstOrDefault();

    if (product != null)
    {
        numChanges = cart.AddToCart(product);
    }

    if (numChanges > 0)
    {
        JToken json = JObject.Parse("{ 'id' : " + id + " , 'name' : '" +  
                      product.Name + "', 'price' : '" + product.Price + "', 
                      'count' : '" + numChanges + "' }");
        return new HttpStatusCodeResult(200, json.ToString());
    }
    else
    {
        return new HttpStatusCodeResult(400, "Product couldn't be added to the cart");
    }

} }

After the method returns with a HTTP 200 code, then I get the "net:: ERR_CONNECTION_RESET" in Chrome (and error in other browsers).该方法返回 HTTP 200 代码后,我在 Chrome 中得到“net:: ERR_CONNECTION_RESET”(在其他浏览器中出现错误)。 It's important to note that the 200 code handler in the jQuery .ajax call is never called.需要注意的是,jQuery .ajax 调用中的 200 代码处理程序从未被调用。 the connection is reset immediately upon returning.返回后立即重置连接。

According to some blogs, I should increase the maxRequestLength, which I have:根据一些博客,我应该增加 maxRequestLength,我有:

<system.web>
    <httpRuntime targetFramework="4.5" 
                 maxRequestLength="10485760" executionTimeout="36000" />
</system.web>

But this hasn't worked.但这并没有奏效。

Update (13 March 2015):更新(2015 年 3 月 13 日):

So I changed the $.ajax call to respond to success and error as opposed to specific status codes like so:所以我改变了 $.ajax 调用来响应成功和错误,而不是像这样的特定状态代码:

$.ajax({
    url: "/Shop/AddToCart/" + id,
    contentType: "application/json; charset=utf-8",
    type: "POST",
    accepts: {
        json: "application/json, text/javascript"
    },
    success: function (data, textStatus, jqXHR) {
        // jqXHR.status contains the Response.Status set on the server
        alert(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        // jqXHR.status contains the Response.Status set on the server
        alert(jqXHR.statusCode + ": " + jqXHR.status);
    }
});

Now, even though I am returning back a 200 from my controller code, the error block is being hit.现在,即使我从控制器代码返回 200,错误块也被命中。 So, that's progress.所以,这就是进步。 BUT, the textStatus is simply "error" and jqXHR.status is simply 0.但是, textStatus 只是“错误”,而 jqXHR.status 只是 0。

Any ideas?有任何想法吗?

I have had this same problem.我也遇到过同样的问题。 In my situation, the inner exception message contained a \\r\\n character.在我的情况下,内部异常消息包含一个\\r\\n字符。 After testing, I realized that the statusDescription parameter in HttpStatusCodeResult did not like this.测试后,我意识到,在HttpStatusCodeResult状态说明参数不喜欢这个。 (I'm not sure why) I simply used the code below to remove the characters and everything then worked as expected. (我不知道为什么)我只是使用下面的代码来删除字符,然后一切都按预期工作。

exception.Message.Replace("\r\n", string.Empty);

Hopefully this will help someone else!希望这会帮助别人! :) :)

I have solved the issue.我已经解决了这个问题。 I don't understand why this is, but it seems as though the more robust solution of returning an instance of HttpStatusCodeResult is what was causing the connection reset.我不明白为什么会这样,但似乎返回 HttpStatusCodeResult 实例的更强大的解决方案是导致连接重置的原因。 When I set the Response status code and return a JToken object like so:当我设置响应状态代码并返回一个 JToken 对象时:

[HttpPost]
public JToken AddToCart(int id)
{
    int numChanges = 0;
    var cart = ShoppingCart.GetCart(httpContextBase);
    Data.Product product = null;
    _productRepository = new ProductRepository();

    product = _productRepository.GetProducts()
       .Where(x => x.ProductID == Convert.ToInt32(id)).FirstOrDefault();

    if (product != null)
    {
        numChanges = cart.AddToCart(product);
    }

    if (numChanges > 0)
    {
        JToken json = JObject.Parse("{ 'id' : " + id + " , 'name' : '" + 
                    product.Name + "', 'price' : '" + product.Price + "', 
                    'count' : '" + numChanges + "' }");

        Response.StatusCode = 200;
        return json;
    }
    else
    {
        Response.StatusCode = 400;
        Response.StatusDescription = "Product couldn't be added to the cart";
        return JObject.Parse("{}");
    }
}

Everything works just fine.一切正常。

I would LOVE to understand why.我很想知道为什么。 But, for now, that's my solution.但是,就目前而言,这就是我的解决方案。

I had this issue too, and also thought it was an SSL issue, but in my case selecting the data out of the object I was returning into a new anonymous object fixed the issue, eg:我也有这个问题,也认为这是一个 SSL 问题,但在我的情况下,从对象中选择数据我返回到一个新的匿名对象修复了这个问题,例如:

[HttpGet]
public IActionResult GetContact(int contactId)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    Contact contact = _contactRepository.Get(contactId);

    if (contact == null)
    {
        return NotFound();
    }

    return Ok(new {contact.FirstName, contact.LastName);
}

I have no idea why that worked, the above is just an example, in my actual case I had a dozen properties, including properties that were other objects.我不知道为什么会这样,上面只是一个例子,在我的实际情况中,我有十几个属性,包括其他对象的属性。 I copied all of the properties to anonymous object and it started working.我将所有属性复制到匿名对象并开始工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM