gpt4 book ai didi

c# - 在 .Net 6.0 中的隔离进程 Azure Functions 中使用 Newtonsoft.Json

转载 作者:行者123 更新时间:2023-12-02 06:12:14 25 4
gpt4 key购买 nike

我当前使用 Azure 应用程序配置来存储所有配置数据。当我读取数据时,我想使用 Newtonsoft.Json 而不是默认的 System.Text.Json 将我的数据正确转换为自定义类型。

不幸的是,我找不到一种方法来告诉 Program.cs 文件中的 HostBuilder 使用 Newtonsoft.Json 而不是 System.Text.Json。我的所有转换器都是使用 Newtonsoft.Json 编写的,我真的不想将它们全部迁移到 System.Text.Json。

举个例子:


public Enum SampleEnum
{
[Description("Sample")] SampleAbc
}

public class SampleConfig
{
public SampleEnum ConfigEnumA {get; set;}
}

// configuration is the IConfiguration object from Microsoft.Extensions.Configuration

var sampleConfig = new SampleConfig()
configuration.GetSection("section").bind(sampleConfig);

DescriptionSample 是来自 Azure 应用程序配置的字符串,理想情况下我当前的 Newtonsoft.Json 转换器应将其转换为绑定(bind)对象 SampleConfig 时的 SampleAbc 枚举值。这使我可以在代码中保持类型安全。

这意味着 ConfigEnumA 的值应为 SampleEnum.SampleAbc 而不是 Sample

我已经尝试过使用,但它不起作用,尽管我正在使用 HTTP 触发器而不是 Web 应用程序

var hostBuilder = new HostBuilder().ConfigureServices(services => 
{
services.AddMvc().AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters = <my-custom-converters>
}
)
});

如果无法在非 Mvc 应用程序的 Azure Function 应用中使用 Newtonsoft.Json,那么有人可以帮助使用 System.Text.Json 实现相同的行为吗? >?

感谢您的帮助。干杯。

最佳答案

  • 据我所知,Services.AddMvcCore().AddJsonOptions(...)用于 System.Text.Jsonbuilder.services.AddMvcCore().AddNewtonsoftJson(options => 可用于Newtonsoft.json

  • 如果您想使用Newtonsoft,请添加 Microsoft.AspNetCore.Mvc.NewtonsoftJson作为 NuGet 的依赖项,其中包含 AddNewtonsoftJson()扩展名。

dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson --version 7.0.0

enter image description here

  • 感谢@Nate1zn ,我找到了如何使用Newtonsoft.Json在 Azure Function 应用中,您可以将启动添加到您的函数项目中,如下所示:
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection

[assembly: FunctionsStartup(typeof(NewtonsoftjsonfunctionApp.functionsample))]
namespace NewtonsoftjsonfunctionApp
public class functionsample : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.services.AddMvcCore().AddNewtonsoftJson(options =>
{
options.SerializerSettings.//json settings
}
}
}

关于c# - 在 .Net 6.0 中的隔离进程 Azure Functions 中使用 Newtonsoft.Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74677503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com