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

10,104

Solution 1

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.

Solution 2

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! :)

Share:
10,104
sshirley
Author by

sshirley

Updated on June 15, 2022

Comments

  • sshirley
    sshirley almost 2 years

    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?