mar*_*c_s 9 c# azure-functions json-serialization system.text.json .net-6.0
我正在尝试从刚刚移植到 .NET 6(隔离托管模型)的 Azure Function 中的代码调用 Web API。我利用迁移的机会摆脱了 RestSharp 和 Json.NET 依赖项,现在只使用HttpClient和System.Text.Json处理 HTTP 调用和 JSON 内容。
我确实尝试使用这段代码,它看起来是完美的组合:
Project project = await _httpClient.GetFromJsonAsync<Project>(someUrl);
if (project != null)
{
HttpResponseData callResponse = req.CreateResponse(HttpStatusCode.OK);
await callResponse.WriteAsJsonAsync(project);
return callResponse;
}
Run Code Online (Sandbox Code Playgroud)
通话工作正常 - 我Project顺利取回了我的对象。
但不幸的是,使用这段代码,我似乎无法影响响应中 JSON 的渲染方式 - 例如,在我的例子中,null返回值(我想避免),并且所有属性名称都大写(“Institute”,而不是“研究所”、“LeadLanguage”而不是“leadLanguage”)。
没问题 - 只需使用一个JsonSerializerOptions对象并定义你想要的,我想。当然,我可以创建这样一个对象 - 但我要把它插入哪里?
WriteAsJsonAsync似乎不支持任何序列化器选项作为参数(为什么??),并且我找不到全局定义我的方法JsonSerializerOptions(因为我找到的所有内容似乎都基于该services.AddControllers().AddJsonOptions()方法 - 自从我的Azure函数以来我就无法使用该方法AddControllers其启动代码中没有该部分)。
我已经通过这样做得到了我想要的结果:
if (project != null)
{
HttpResponseData callResponse = req.CreateResponse(HttpStatusCode.OK);
callResponse.Headers.Add("Content-Type", "application/json");
string jsonResponse = JsonSerializer.Serialize(project, settings);
await callResponse.WriteStringAsync(jsonResponse, Encoding.UTF8);
return callResponse;
}
Run Code Online (Sandbox Code Playgroud)
但这似乎有点复杂和“低级” - 手动将结果对象转换为字符串,必须手动设置Content-Type和所有......
Azure Function(.NET 6 隔离托管模型)中真的没有办法全局指定JsonSerializerOptions或WriteAsJsonAsync使用特定的序列化器选项对象进行调用吗?
mar*_*c_s 27
在我发布问题 10 秒后 -当然!- 我跑过马路用 Azure Function 来做这件事。
像这样的东西:
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(s =>
{
s.AddHttpClient();
// define your global custom JSON serializer options
s.Configure<JsonSerializerOptions>(options =>
{
options.AllowTrailingCommas = true;
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.PropertyNameCaseInsensitive = true;
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助其他人!