D
D
Dmitry2019-10-04 13:27:27
ASP.NET
Dmitry, 2019-10-04 13:27:27

When using signalR, it throws a System.InvalidOperationException: "The session cannot be established after the response has started."?

when you click on the "Add to Cart" button, the script is launched:

$('#AddCart').on('click', function (event) {
    var productId = $('#userInput').val();
    var quantityInProduct = $('input[name="quantityInProduct"][data-id="' + productId + '"]').val();
    connection.invoke("QuantityOfCart", productId, quantityInProduct).catch(function (err) {
        return console.error(err.toString());
    });
});

script runs method in Hub.cs
public async Task QuantityOfCart(int productId, int quantityInProduct)
{
  Product product =   repositoryProduct.Products.FirstOrDefault(p => p.ProductID == productId);
  if (product != null){cart.AddItem(product, quantityInProduct);}

  int quantityOfCart = cart.Lines.Count();
  await Clients.All.SendAsync("SendQuantityOfCart", quantityOfCart);}

and on the line "cart.AddItem(product, quantityInProduct);" throws an exception:
System.InvalidOperationException: "The session cannot be established after the response has started."
here is the code where it throws the error
public static void SetJson(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

I understand the problem is that SetJson was launched via invoke, but I can’t figure out how to fix it.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question