dotnet core 3.0 不支持 DataMember 属性 [英] DataMember Attribute is not honored in dotnet core 3.0
问题描述
我创建了一个示例 dotnet core 3.0 Web API 项目并进行了以下更改,
I created a sample dotnet core 3.0 Web API project and did the following changes,
- 创建模型类 TestData
using System.Runtime.Serialization;
namespace WebApplication17.Models
{
[DataContract]
public class TestData
{
[DataMember(Name = "testaction")]
public string Action { get; set; }
}
}
然后我在控制器 WeatherForecastController
中进行了更改,以添加一个 post 端点
Then I made changes in controller WeatherForecastController
, to add a post endpoint
[HttpPost("package/{packageName}/version/{version}")]
public void Post(string packageName, string version, [FromBody] TestData activityPayload)
{
Console.WriteLine(activityPayload.Action);
}
现在我打电话给邮递员或用身体卷曲
Now I made a call from postman or curl with body
{
"testaction": "action"
}
仍然在WeatherForecastController
的Post
方法中,activityPayload.Action
为null.
我期待它是行动"
推荐答案
Asp.Net Core 3 默认不支持[DataContract]
、[DataMember]
基于这个 Github 问题,他们看起来不会很快添加它
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
如果您想切换回使用 Newtonsoft.Json
的先前默认设置,它确实支持这些属性,那么您必须执行以下操作:
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:
安装 Microsoft.AspNetCore.Mvc.NewtonsoftJsonNuGet 包.
在 ConfigureServices()
中添加对 AddNewtonsoftJson()
public void ConfigureServices(IServiceCollection services) {
//...
services.AddControllers()
.AddNewtonsoftJson(); //<--
//...
}
这篇关于dotnet core 3.0 不支持 DataMember 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!