简体   繁体   中英

ASP.Net Core 3.1 WEB API - Controller method doesn't return correct JSON

I have an ASP.Net Core 2.2 Website that I have upgraded to ASp.Net Core 3.0. Most of the WEB API methods works as expected and returns data just as before the upgrade.

But this API methods returns an array with empty elements:

    [Route("api/TripAnalysis/{id:int}")]
    public List<TurAnalyse> GetTripAnalysis(int id)
    {
        var x = new List<TurAnalyse>() { new TurAnalyse { ArtId = 1, ArtNavn = "Havørn", C1 = "X", Su = false } };
        return x;
    }

The TurAnalyse model class is here:

public class TurAnalyse
{
    public int ArtId;
    public bool Su;
    public string ArtNavn;

    public string C1;
    public string C2;
    public string C3;
    public string C4;
    public string C5;
    public string C6;
}

I get this back when calling the controller method:

[{}]

So it returns an array with 1 element, but no properties or values - and don't understand why?

The default JSON Serializer in .NET Core 3.1 does not support serializing fields. So either switch them to properties, switch to JSON.NET, or jump to .NET Core 5 which does support fields. eg

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers().AddJsonOptions(o => o.JsonSerializerOptions.IncludeFields = true); 
}

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