我一直在尝试将JsonApiSerializer(https://github.com/codecutout/JsonApiSerializer)设置为输入和输出的默认序列化器,这样我就可以为带有Ember数据的Ember应用程序提供一个符合json:api的.NET服务器。
我已经通过将以下代码写入Startup.cs文件成功地设置了输出序列化程序:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<Context>(options => options.UseSqlServer(Configuration.GetConnectionString("myDb")));
var sp = services.BuildServiceProvider();
var logger = sp.GetService<ILoggerFactory>();
var objectPoolProvider = sp.GetService<ObjectPoolProvider>();
services.AddMvc(opt =>
{
var serializerSettings = new JsonApiSerializerSettings();
**
var jsonApiFormatter = new NewtonsoftJsonOutputFormatter(serializerSettings, ArrayPool<Char>.Shared, opt);
opt.OutputFormatters.RemoveType<NewtonsoftJsonOutputFormatter>();
opt.OutputFormatters.Insert(0, jsonApiFormatter);
**
var mvcNewtonsoftSettings = new MvcNewtonsoftJsonOptions();
var jsonApiInputFormatter = new NewtonsoftJsonInputFormatter(logger.CreateLogger<NewtonsoftJsonInputFormatter>(), serializerSettings, ArrayPool<Char>.Shared, objectPoolProvider, opt, mvcNewtonsoftSettings);
opt.InputFormatters.RemoveType<NewtonsoftJsonInputFormatter>();
opt.InputFormatters.Insert(0, jsonApiInputFormatter);
//opt.InputFormatters.OfType<NewtonsoftJsonInputFormatter>().FirstOrDefault().SupportedMediaTypes.Add("application/vnd.api+json");
}).AddNewtonsoftJson();
}
但是输入部分还不能工作!
我一直在尝试从一个Ember应用程序中接收代码,该应用程序遵循以下结构:
{
"data":
{
"type": "manufacturer",
"name": "Fabricante 1",
"relationships": {
"products": {
"data": [
{
"type": "product",
"id": "1"
},
{
"type": "product",
"id": "2"
}
]
}
}
}
}
用于POST制造商的.NET服务器绑定模型如下所示:
public class CreateManufacturerBindingModel
{
public string Type { get; set; } = "manufacturer";
public string Name { get; set; }
public AssignProductBidingModel[] Products { get; set; }
}
public class AssignProductBidingModel
{
public string Type { get; set; } = "product";
public int Id { get; set; }
}
我已经尝试了这些代码的一些变体一段时间了,我所能得到的只是CreateManufacturerBindingModel的**“Name”和“Products”属性的Null**值
有人知道为什么我在.NET服务器上总是得到空值吗?
感谢您的关注!
1条答案
按热度按时间dohp0rv51#
默认情况下,ASP.NET Core 3.1将使用System.Text.Json序列化程序。您尝试使用的JsonApiSerializer需要Newtonsoft。您可以通过安装以下nuget包在项目中使用Newtonsoft。(不要使用最新的5.0.0版本,因为它需要net5.0)
然后,您可以按如下方式配置序列化程序。它不允许您替换整个
SerizlierSettings
,但JsonApiSerializerSettings
只设置了几个属性,因此我们可以直接设置它们最后,您需要更新模型,使其包含
Id
字段。完成后,它应该开始将对象序列化和反序列化为JsonApi对象