Skip to content
Advertisement

Miagration Asp.Net Core 2 to .Net 6 gave me XMLHttpRequest problems

I folks, I just migrated my ASP.Net Core 2 MVC app to .Net 6, but since that, I have a weird problem: my XMLHttpRequest responses texts are always empty, “{}” or [{},{},{},{}] for arrays, despite my backend really returning data.

Here’s an example of a controler method (TestLoad) returning a simple class (TestClass). Notice that when I break on the return line, the value returned is ok, or at least I don’t see anything wrong (see image for debug infos): backend

public class TestClass
{
   public int id = 0;
   public string title = "Title";
   public bool active = false;
}

public JsonResult TestLoad()
{
   TestClass testClass = new TestClass();
   testClass.id = 10;
   testClass.title = "Yeah man!";
   testClass.active = true;

   JsonResult jsonRes = Json(testClass);
   return jsonRes;
}

But once on the front end, I got an empty object, not undefined nor null, but really an empty object (see image for debug infos): frontend

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4) {
        if (xmlhttp.status == 200) {
            var dt = JSON.parse(xmlhttp.responseText);
            if (dt == 'err') {   
                alert('error');
            }
            else if (dt !== null) {                    
                alert(dt.title);                    
            }                
        }
        else {
            alert(xmlhttp.status);
        }
    }
}

ldwait(false, false);
xmlhttp.open("GET", rv + "ajxGame/TestLoad", true);
xmlhttp.setRequestHeader('Cache-Control', 'no-store');

xmlhttp.setRequestHeader("Content-Type", "application/json");

xmlhttp.send();

Any help would be greatly appreciated since I completely clueless of what happened. Again, my code hasn’t changed, but my project has migrated from .Net Core 2 to .Net 6.

Thank you

Advertisement

Answer

Actually, my error was simply that I forgot to add { get; set; } on each property of my TestClass in the backend part! It worked without it in .Net Core 2, but it seems like this is now mandatory in .Net 6

public class TestClass
{
   public int id {get; set;} = 0;
   public string title {get; set;} = "Title";
   public bool active {get; set;} = false;
}

…thanks to those who attempted an answer!

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement