在 Asp.Net Core 中设置 JsonContent 的默认值
我正在尝试在 Asp.Net Core 6.0 中发送包含多部分表单数据(一个文件和一个 Json 字段)的 POST 请求。代码的相关部分是
...
using var request = new HttpRequestMessage(HttpMethod.Post, "myrequest");
using var content = new MultipartFormDataContent
{
{new StreamContent(image), "data", "file.ext"},
{JsonContent.Create(myObject), "Object"}
};
request.Content = content;
using var res = await _httpClient.SendAsync(request);
...
This Works,只不过公司政策是以 PascalCase 序列化 Json 字段,而 JsonContent
使用的 JsonSerializerDefaults.Web
默认为驼峰式。
我可以通过编写来修复这个特定的实例
{JsonContent.Create(myObject, null, new JsonSerializerOptions() { PropertyNamingPolicy = null }), "Object"}
,但问题是我必须在构建此类请求的任何地方执行此操作。
我的问题:我可以在全局某处为 JsonContent
设置 PascalCase 吗?
我可以通过 builder.Services.AddControllers().AddJsonOptions(options =>) 为控制器设置此选项; 选项.JsonSerializerOptions.PropertyNamingPolicy = null);
,
并且存在诸如 如何设置默认 json 序列化之类的问题设置 HttpClient (WinForms) ,但它们似乎都不适用于 Asp.Net Core 中使用 System.Text.Json
的 JsonContent
。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,没有选项可以告诉
JsonContent.Create()
使用全局 JsonSerializerOptions。但是您可以使用选项模式来检索全局 JsonSerializerOptions,您已使用
AddJsonOptions(...);
添加。Program.cs:
控制器中注入的选项:
为了进一步简化事情,您可以使用静态辅助方法,这样您就不需要传递类型,并且可以可以只传递选项。
PascalCaseHelper.cs:
As far as I know, there is no option for telling
JsonContent.Create()
to use the global JsonSerializerOptions.BUT you could use the options pattern to retrieve the global JsonSerializerOptions, you've added with
AddJsonOptions(...);
.Program.cs:
Options injected in Controller:
To simplify things a bit more, you could use a static helper method, so you don't need to pass the type and you can just pass the options.
PascalCaseHelper.cs: