C# Post AJAX empty json result

Viewed 203

I make a POST ajax request to perform an action and return a result without reloading the page.
For this I use a JSON Result, the problem is that when my action "foo.DoSyncAction(id)" takes a while to execute, the messages returned are null.
For example when an exception is raised, the exception is caught, but his message is null.

The same thing happens when no exception is thrown, "actionResult" is null.
If I use an action that takes less time, the returned messages are not null or empty.
And it doesn't happen in debug mode, the message returned to my page is not null.
I think I forgot or I'm doing something wrong, but I can't figure out what is wrong.

[HttpPost]
public JsonResult SomeAction(int id)
{
    try
    {
        Foo foo = new Foo();
        var actionResult = foo.DoSyncAction(id);

        return Json(new { ok = true, data = actionResult }, JsonRequestBehavior.AllowGet); ;
    }
    catch (Exception ex)
    {

        return Json(new { data = ex == null ? "null ex" : (string.IsNullOrEmpty(ex.Message) ? "this exception is empty" : ex.Message) }, JsonRequestBehavior.AllowGet);
    }
}

My AJAX query :

$.ajax({
    url: '@Url.Action("SomeAction", "MyController")',
    dataType: 'json',
    data: { id: myID },
    type: 'POST',
    success: function (response) {
        if (response.ok) {
            // When everything is ok
            console.log(response.data);
        } else {
            // When an exception is thrown
            console.log("An error occurred :  " + response.data);

        }
    },
    error: function (error) {
        console.log("An error occurred :  " + error.responseText);
    }
});

Here is an example of a similar situation : dotnetfiddle.net/cG2L0u I use Sagnalrac example with a 10 sec wait, and my problem occurred. The list of items is no longer displayed and the console.log returns an empty string. I'm using ASP MVC 5 with .NET 4.8

1 Answers

I solved my problem, but I still have some misunderstandings.

My method returns an exception systematically related to the account executing the method (that's why in debug it works, whereas on a web server it doesn't, because the accounts used are different).

The weird thing is that my method does throw an exception, I even manage to catch it and send it by mail. But when the controller catches the exception, she is empty or null. I'll try to take a closer look at this problem.

Once I fixed the problem, I tried to add a timeout of 2 minutes, and no problem occurred (I think in the example, dotnetfiddle has a different configuration than mine, that's why no exception shows up).

Related