gpt4 book ai didi

c# - ASP.NET Core 中的 SnakeCaseNamingStrategy 和 JsonPatch

转载 作者:行者123 更新时间:2023-11-30 22:59:12 25 4
gpt4 key购买 nike

在使用ApsNetCore.JsonPatch (2.1.1) 包?

我遇到了路径未解析的问题,因为我的模型中的属性是 PascalCase,但 JsonPatch 中的路径是 SnakeCase。

在这种情况下,我必须将 JsonPatchDocument 上的 ContractResolver 设置为 Startup.cs 文件中默认/全局注册的 ContractResolver。

它有效,但我必须为我要实现的每个补丁路线执行此操作。

启动配置:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
services
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
})
}

Controller :

[HttpPatch("{id}"]
[Consumes(MediaTypeNames.Application.Json)]
public async Task<IActionResult> Patch(string id,
[FromBody] JsonPatchDocument<Entity> patchEntity)
{
...
patchEntity.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
patchEntity.ApplyTo(entity);
...

最佳答案

似乎没有简单的方法来影响 ContractResolver在创建 JsonPatchDocument<T> 的实例时使用.此类的实例由 TypedJsonPatchDocumentConverter 创建,就像这个代码片段显示的那样:

var container = Activator.CreateInstance(
objectType,
targetOperations,
new DefaultContractResolver());

这里很明显DefaultContractResolver在创建 JsonPatchDocument<T> 的实例时被硬编码为第二个参数.

使用 ASP.NET Core MVC 时处理此问题的一个选项是使用 Action Filter ,它允许对传递到操作中的任何参数进行更改。这是一个基本示例:

public class ExampleActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext ctx)
{
// Find a single argument we can treat as IJsonPatchDocument.
var jsonPatchDocumentActionArgument = ctx.ActionArguments.SingleOrDefault(
x => typeof(IJsonPatchDocument).IsAssignableFrom(x.Value.GetType()));

// Here, jsonPatchDocumentActionArgument.Value will be null if none was found.
var jsonPatchDocument = jsonPatchDocumentActionArgument.Value as IJsonPatchDocument;

if (jsonPatchDocument != null)
{
jsonPatchDocument.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
}
}
}

ActionExecutingContext此处传递的类包括 ActionArguments属性,此示例用于尝试查找类型为 IJsonPatchDocument 的参数.如果找到一个,我们将覆盖 ContractResolver相应地。

为了使用这个新的 Action 过滤器,您可以将它添加到 Controller 、 Action 或全局注册它。以下是全局注册的方法(其他选项有很多答案,所以我不会在这里深入探讨):

services.AddMvc(options =>
{
options.Filters.Add(new ExampleActionFilterAttribute());
});

关于c# - ASP.NET Core 中的 SnakeCaseNamingStrategy 和 JsonPatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52401276/

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