gpt4 book ai didi

c# - asp.net 核心 3 webapi : Route or Bind parameters (query or posted) with hyphens in their name

转载 作者:行者123 更新时间:2023-12-04 09:41:08 27 4
gpt4 key购买 nike

我希望一个 Action 签名像

[HttpPost]
public string Post(string thirdPartySpecifiedParameter)

将自动绑定(bind)连字符的查询参数

controller?third-party-specified-parameter=value

或 JSON 发布值
{ "third-party-specified-parameter":"value" }

并将其分配给 thirdPartySpecifiedParameter但事实并非如此。路由文档处理在 Urls 路径中映射连字符的示例,但不涉及对 C# 无效的绑定(bind)参数和字段名称。

将传入的连字符名称绑定(bind)到匹配的 C# 参数的最简单方法是什么?

最佳答案

首先,问题在于绑定(bind)而不是路由,最简单的可用解决方案是使用 BindingAttribute由.Net 提供。限制——不是一个新的——是您需要一个不同的 BindingAttribute 用于查询参数、Json Body 和 Form 帖子。

[HttpPost]
public string Post(
[FromBody]PostModel model,
[FromQuery(Name="kebab-case-query-param")]string kebabCaseQueryParam)
[FromQuery(Name="...")]处理查询字符串参数
对于 Json 帖子,您必须使用 [FromBody]方法签名中的属性,并定义一个模型,并放置一个 Attribute在要绑定(bind)的属性上。 Newtonsoft.Json或 new-in-core-3 System.Text.Json使用略有不同 Attribute名称:
public class PostModel
{
//This one if you are using Newtonsoft.Json
[JsonProperty(PropertyName = "kebab-case-json-field")]

//This one of you are using the new System.Text.Json.Serialization
[JsonPropertyName("kebab-case-json-field")]

public string kebabCaseProperty { get; set; }
}
回到您的 Startup.cs , 要使用 Newtonsoft,您还需要 AddMvc() , 而对于新的 System.Text.Json ,你没有。像这样的东西:
    public void ConfigureServices(IServiceCollection services)
{
//if using NewtonSoft
services.AddMvc().AddNewtonsoftJson();

//if using System.Text.Json
//dotnet new webapi for netcore3 generates this code:
services.AddControllers();

}
要在 NetCore3 下以这种方式使用 Newtonsoft Json,您需要依赖 nuget 包 Microsoft.AspNetCore.Mvc.NewtonsoftJson

关于c# - asp.net 核心 3 webapi : Route or Bind parameters (query or posted) with hyphens in their name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62327246/

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