【问题标题】:asp.net core 3 webapi : Route or Bind parameters (query or posted) with hyphens in their nameasp.net core 3 webapi:路由或绑定参数(查询或发布),名称中带有连字符
【发布时间】:2020-06-11 14:55:35
【问题描述】:

我希望像这样的 Action 签名

[HttpPost]
public string Post(string thirdPartySpecifiedParameter)

会自动绑定连字符的查询参数

controller?third-party-specified-parameter=value

或 JSON 发布值

{ "third-party-specified-parameter":"value" }

并将其分配给thirdPartySpecifiedParameter,但它没有。 routing 文档处理在 Urls 路径中映射连字符的示例,但不涉及对 C# 无效的 binding 参数和字段名称。

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

【问题讨论】:

  • 很可能您正在使用新的默认System.Text.Json,它还不能处理这个问题
  • 这只是 aspnetcore 3.1.3 上的 dotnet new webapi 模板,模板是最新的,我添加的唯一代码是这里描述的一种方法。
  • nb 我已经编辑了 Q,因为我意识到我真的在问 binding 而不是路由
  • Nkosi,是的,我明白你的意思——对于 json 发布,这就是问题所在。随意写一个答案,否则我会写一个涵盖我的两个用例

标签: c# asp.net-core


【解决方案1】:

首先,问题在于绑定而不是路由,最简单的可用解决方案是使用 .Net 提供的BindingAttribute。限制 - 不是新限制 - 是您需要不同的 BindingAttribute 用于查询参数、Json 正文和表单帖子。

[HttpPost]
public string Post(
    [FromBody]PostModel model,
    [FromQuery(Name="kebab-case-query-param")]string kebabCaseQueryParam)

[FromQuery(Name="...")] 处理查询字符串参数

对于Json帖子,必须在方法签名中使用[FromBody]属性,并定义模型,并在属性上放置Attribute进行绑定. 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    • 2019-04-07
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    相关资源
    最近更新 更多