简体   繁体   中英

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. I've enabled SSL on the site. I've created a self-signed certificate for the site. When I make an ajax POST call to a MVC controller:

$.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". It doesn't work in any other browser either.

I know this error has something to do with 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.

Any ideas?

Update (13 March 2015):

So upon further investigation, I found that the MVC controller action is indeed being called. In that method, I am returning an instance of 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). It's important to note that the 200 code handler in the jQuery .ajax call is never called. the connection is reset immediately upon returning.

According to some blogs, I should increase the maxRequestLength, which I have:

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

But this hasn't worked.

Update (13 March 2015):

So I changed the $.ajax call to respond to success and error as opposed to specific status codes like so:

$.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. So, that's progress. BUT, the textStatus is simply "error" and jqXHR.status is simply 0.

Any ideas?

I have had this same problem. In my situation, the inner exception message contained a \\r\\n character. After testing, I realized that the statusDescription parameter in HttpStatusCodeResult did not like this. (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. When I set the Response status code and return a JToken object like so:

[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:

[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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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