Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net Core 3 [JsonIgnore] not working when requesting single resource

in my .net Core 3.0 Api the [JsonIgnore] Attribute is not working as excepted. Im using System.Text.Json

instead of the old Newtonsoft.Json

When i'm using my resource that returns a list of Objects, for example:

/api/Object/

the objects are serialized like this:

  [
  {
    "id": 1,
    "date": "2020-02-12T08:45:51.502",
    "userId": 1,
    "tags": [
      {
        "name": "string"
      }
    ]
  }
]

But when I request a single result

/api/Object/{id}

the full object gets serialized like this:

    {
  "user": {
    "hasAccess": false,
    "id": 1,
    "userName": "***",
    "normalizedUserName": "***",
    "email": "***",
    "normalizedEmail": "***",
    "emailConfirmed": true,
    "passwordHash": "***",
    "concurrencyStamp": "***",
    "phoneNumberConfirmed": false,
    "twoFactorEnabled": false,
    "lockoutEnabled": true,
    "accessFailedCount": 0
  },
  "lazyLoader": {},
  "id": 1,
  "date": "2020-02-12T08:45:51.502",
  "userId": 1,
  "tags": [
    {
      "name": "string"
    }
  ]
}

The class with the JsonIgnore Attribute looks like this:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text.Json.Serialization;
 public class Object
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public DateTime Date { get; set; }
    [ForeignKey("User")]
    public int UserId { get; set; }
    [JsonIgnore]
    public virtual User User { get; set; }
}

This is my WebApi Controller Class:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Models;
using Services;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

  [Route("api/object")]
    [ApiController]
    [Authorize(Roles = Roles.ACCESS_GRANTED)]
    public class ObjectController : AbstractController
    {
        private readonly ObjectService objectService;

        public ObjectController(IDataService<Object> service, ExtendedUserManager manager) : base(manager)
        {
            objectService = (ObjectService)service;
        }

        // GET: api/Object
        [HttpGet]
        public IActionResult Get()
        {
            List<Object> object = objectService.GetAll();
            return Ok(object);
        }




        // GET: api/Object/5
        [HttpGet("{id}", Name = "GetObject")]
        public IActionResult Get(int id)
        {
            Object object = objectService.Get(id);

            if (object == null)
            {
                return NotFound(string.Format("Object with Id {0} could not be found", id));
            }

            return Ok(object);
    }
}

My csproj File:

    <Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
    <IsPackable>false</IsPackable>
    <SpaRoot>ClientApp\</SpaRoot>
    <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>

    <!-- Set this to true if you enable server-side prerendering -->
    <BuildServerSideRenderer>false</BuildServerSideRenderer>
    <RootNamespace>Project</RootNamespace>
    <Configurations>Debug;Release;</Configurations>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
    <PackageReference Include="log4net" Version="2.0.8" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="3.0.3" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.1" />
    <PackageReference Include="SendGrid" Version="9.12.6" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.6.0" />
  </ItemGroup>

  <ItemGroup>
    <!-- Don't publish the SPA source files, but do show them in the project files list -->
    <Content Remove="$(SpaRoot)**" />
    <None Remove="$(SpaRoot)**" />
    <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
  </ItemGroup>

  <Target Name="Restore">
    <MSBuild Projects="$.\open-success.sln" Targets="Restore" />
  </Target>

  <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
    <!-- Ensure Node.js is installed -->
    <Exec Command="node --version" ContinueOnError="true">
      <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
    </Exec>
    <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
    <Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
  </Target>

  <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
    <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />


    <!-- Include the newly-built files in the publish output -->
    <ItemGroup>
      <DistFiles Include="$(SpaRoot)dist\**; $(SpaRoot)dist-server\**" />
      <DistFiles Include="$(SpaRoot)node_modules\**" Condition="'$(BuildServerSideRenderer)' == 'true'" />
      <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
        <RelativePath>%(DistFiles.Identity)</RelativePath>
        <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
        <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
      </ResolvedFileToPublish>
    </ItemGroup>
  </Target>

</Project>

And my Startup:

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {


            services.AddCors();


            services.AddControllers();



        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseCors(builder => builder.AllowAnyHeader().AllowAnyOrigin().WithMethods("*"));


            app.UseDeveloperExceptionPage();



            app.UseHttpsRedirection();


            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
            });


        }
    }

Am I missing something or is this a Bug?

Update:

I noticed an other strange behavior, when I return a newly created Object instead of the object from the database, everything works perfectly fine.

 [HttpGet("{id}", Name = "GetObject")]
    public IActionResult Get(int id)
    {
        // Object object= objectService.Get(id);
        Object object= new Object ();
        object.User = new User();

        if (object== null)
        {
            return NotFound(string.Format("object with Id {0} could not be found", id));
        }

        return Ok(object);
    }
like image 334
mic Avatar asked Feb 12 '20 09:02

mic


People also ask

How to ignore property in Json?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.

Can I optionally turn off the JsonIgnore attribute at runtime?

Yes, add prop. PropertyName = prop. UnderlyingName; inside the loop in the resolver. This will cause the property to use its original name.

What is JsonIgnore in C#?

If you are using Json.Net attribute [JsonIgnore] will simply ignore the field/property while serializing or deserialising.

What is System Text JSON?

Text. Json. Serialization namespace, which contains attributes and APIs for advanced scenarios and customization specific to serialization and deserialization.


2 Answers

You need:

using Newtonsoft.Json;

Instead of:

using System.Text.Json.Serialization;

The nuget package is Microsoft.AspNetCore.Mvc.NewtonsoftJson. It's no longer included in .net core.

like image 117
Tim Avatar answered Oct 07 '22 08:10

Tim


You can use [JsonIgnore] from System.Text.Json, and it will work if you call serlization/deserialization methods manually. However; built-in .net core seralization system i.e. for controllers, httpclient.GetFromJsonAsync .. etc. [JsonIgnore] attribute is not working as of today.

Looks like internal serialization dont use System.Text.Json and the JsonIgnore attribute has not yet been adapted. In such a case use [IgnoreDataMember] attribute and .net core internal system will ignore such properties and it will work well.

like image 31
freewill Avatar answered Oct 07 '22 08:10

freewill