DataMember Attribute is not honored in dotnet core 3.0
Asp.Net Core 3 does not support [DataContract]
, [DataMember]
by default and it does not look like they would be adding it any time soon based on this Github Issue: System.Text.Json support to System.Runtime.Serialization
If you’d like to switch back to the previous default of using Newtonsoft.Json
, which does honor those attributes, then you'll have to do the following:
Install the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package.
In
ConfigureServices()
add a call toAddNewtonsoftJson()
public void ConfigureServices(IServiceCollection services) {
//...
services.AddControllers()
.AddNewtonsoftJson(); //<--
//...
}
As of .NET Core 3.0 RC1 the System.Text.Json
library does not have support for System.Runtime.Serialization
attributes. You can find an issue on GitHub which is tracking this omission but right now it does not appear that there is any intention to change that.
Option 1: Newtonsoft.Json
What you can do in the interim is switch to using Newtonsoft.Json
as the JSON serializer for ASP.NET Core 3.0 which should restore this functionality (at the cost of not leveraging the System.Text.Json
parser which is a fair bit faster).
First, add a reference to the Microsoft.AspNetCore.Mvc.NewtonsoftJson
package in your project:
<Project Sdk="Microsoft.NET.Sdk.Web">
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" />
</ItemGroup>
</Project>
And then call the extension on your services collection.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson();
}
Option 2: Use System.Text.Json.Serialization
On the other hand, if you're happy to define your models without System.Runtime.Serialization
attributes and use the System.Text.Json.Serialization
attributes instead, then you can do the following:
using System.Text.Json.Serialization;
namespace WebApplication17.Models
{
public class TestData
{
[JsonPropertyName("testaction")]
public string Action { get; set; }
}
}
You can find the full list of supported attributes here: https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonpropertynameattribute?view=netcore-3.0
Add [JsonPropertyName("testaction")]
attribute to the Action
property. This should solve your problem.
See here for more: https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/