在 Asp.Net Core 中设置 JsonContent 的默认值

发布于 2025-01-14 01:25:14 字数 1250 浏览 2 评论 0 原文

我正在尝试在 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.JsonJsonContent

I'm trying to send a POST request with multipart form data (a file and a Json field) in Asp.Net Core 6.0. The relevant part of the code is

...

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, except that the company policy is to serialize Json fields in PascalCase, whereas JsonSerializerDefaults.Web, which is used by JsonContent, defaults to camelCase.

I can fix this specific instance by writing

{JsonContent.Create(myObject, null, new JsonSerializerOptions() { PropertyNamingPolicy = null }), "Object"}

but the problem then becomes that I have to do this anywhere where I build such a request.

My question: can I set PascalCase for JsonContent globally somewhere?

I can set this for the controllers via builder.Services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);,
and there are questions such as How to set default json serialization settings for HttpClient (WinForms) , but none of them seem to apply to JsonContent in Asp.Net Core with System.Text.Json.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如梦 2025-01-21 01:25:14

据我所知,没有选项可以告诉 JsonContent.Create() 使用全局 JsonSerializerOptions

但是您可以使用选项模式来检索全局 JsonSerializerOptions,您已使用 AddJsonOptions(...); 添加。

Program.cs:

builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
});

控制器中注入的选项:

private readonly IOptions<JsonOptions> _JsonOptions;

public YourController(IOptions<JsonOptions> options)
{
    _JsonOptions = options;
}

...

// in your request method:
using var request = new HttpRequestMessage(HttpMethod.Post, "myrequest");
using var content = new MultipartFormDataContent
{
    { new StreamContent(image), "data", "file.ext" },
    { JsonContent.Create(wfc, null, JsonOptions.Value.JsonSerializerOptions), "Object" }
};
request.Content = content;
using var res = await _httpClient.SendAsync(request);

...

为了进一步简化事情,您可以使用静态辅助方法,这样您就不需要传递类型,并且可以可以只传递选项。

PascalCaseHelper.cs:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

using System.Net.Mime;
using System.Text;
using System.Text.Json;

namespace YourNamespace
{
    public static class PascalCaseHelper
    {
        public static StringContent CreateJson(object data, IOptions<JsonOptions> options)
        {
            return new StringContent(
                JsonSerializer.Serialize(data, options.Value.JsonSerializerOptions), 
                Encoding.UTF8,
                MediaTypeNames.Application.Json);
        }
    }
}


// Usage:
{ PascalCaseHelper.CreateJson(myObject, _JsonOptions), "Object" }

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:

builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
});

Options injected in Controller:

private readonly IOptions<JsonOptions> _JsonOptions;

public YourController(IOptions<JsonOptions> options)
{
    _JsonOptions = options;
}

...

// in your request method:
using var request = new HttpRequestMessage(HttpMethod.Post, "myrequest");
using var content = new MultipartFormDataContent
{
    { new StreamContent(image), "data", "file.ext" },
    { JsonContent.Create(wfc, null, JsonOptions.Value.JsonSerializerOptions), "Object" }
};
request.Content = content;
using var res = await _httpClient.SendAsync(request);

...

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:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

using System.Net.Mime;
using System.Text;
using System.Text.Json;

namespace YourNamespace
{
    public static class PascalCaseHelper
    {
        public static StringContent CreateJson(object data, IOptions<JsonOptions> options)
        {
            return new StringContent(
                JsonSerializer.Serialize(data, options.Value.JsonSerializerOptions), 
                Encoding.UTF8,
                MediaTypeNames.Application.Json);
        }
    }
}


// Usage:
{ PascalCaseHelper.CreateJson(myObject, _JsonOptions), "Object" }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文