[英]asp.net core 3 webapi : Route or Bind parameters (query or posted) with hyphens in their name
我希望像这样的动作签名
[HttpPost]
public string Post(string thirdPartySpecifiedParameter)
会自动绑定带连字符的查询参数
controller?third-party-specified-parameter=value
或 JSON 发布值
{ "third-party-specified-parameter":"value" }
并将其分配给thirdPartySpecifiedParameter
但它没有。 路由文档处理在 Urls 路径中映射连字符的示例,但不处理对 C# 无效的绑定参数和字段名称。
将传入的带连字符的名称绑定到匹配的 C# 参数的最简单方法是什么?
首先,问题是关于绑定而不是路由,最简单的可用解决方案是使用.Net 提供的BindingAttribute
。 限制 - 不是新的 - 是您需要不同的 BindingAttribute 查询参数与 Json Body vs Form post。
[HttpPost]
public string Post(
[FromBody]PostModel model,
[FromQuery(Name="kebab-case-query-param")]string kebabCaseQueryParam)
[FromQuery(Name="...")]
处理查询字符串参数
对于 Json 的帖子,你必须在方法签名中使用[FromBody]
属性,并定义一个 model,并在该属性上放置一个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 package Microsoft.AspNetCore.Mvc.NewtonsoftJson
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.