c# - “FromRoute”请求属性的驼峰式序列化
问题描述
在我的 ASP.NET Core 2.1 MVC 应用程序中,我想公开这样的路由:
/address/v1/postcode/{postcode}/street/{street}
我已经这样定义了我的控制器:
[Route("address/v1")]
[ApiController]
public class StreetController : ControllerBase
{
[HttpGet("postcode/{postcode}/street/{street}")]
public ActionResult<GetStreetDetailsResponse> GetStreetDetails([FromRoute] GetStreetDetailsRequest request)
{
throw new NotImplementedException();
}
}
public class GetStreetDetailsRequest
{
[Required]
[StringLength(4, MinimumLength = 4)]
[RegularExpression("^[\\d]+$")]
public string Postcode { get; set; }
[Required]
public string Street { get; set; }
}
public class GetStreetDetailsResponse
{
}
路由按预期解析,但是,框架未反序列化 Postcode 和 Street 值,并且这些属性未在 GetStreetDetailsRequest 中正确填充。
例如,如果我打电话:
http://localhost/address/v1/postcode/0629/street/whatever
当它进入 action 方法时,request.Postcode="{postcode}" 和 request.Street="{street}" 的值。
问题似乎是由于我的属性名称的大小写,因为如果我将 GetStreetDetailsRequest 更改为:
public class GetStreetDetailsRequest
{
[Required]
[StringLength(4, MinimumLength = 4)]
[RegularExpression("^[\\d]+$")]
public string postcode { get; set; }
[Required]
public string street { get; set; }
}
一切正常。但是,我对该解决方案不满意,因为它不遵循传统的 C# 命名标准。
我尝试用 [DataMember(Name="postcode")] 或 [JsonProperty("postcode")] 装饰属性,但这些似乎也被忽略了。
作为记录,在我的 Startup.ConfigureServices() 方法中,我使用了默认的序列化程序,我知道它支持驼峰式案例:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
有没有人有一个解决方案可以让我在请求对象属性名称中使用 Pascal 大小写来公开带有驼峰大小写属性的路由?
解决方案
好吧,你在某种程度上是正确的。这个:
[HttpGet("postcode/{postcode}/street/{street}")]
说你有一个postcode
和一个street
属性,而你一个都没有。如果您希望默认绑定起作用,则大小写必须完全匹配:
[HttpGet("postcode/{Postcode}/street/{Street}")]
推荐阅读
- javascript - 单击后隐藏元素
- c - 后缀符号的堆栈和弹出帮助。打印错误的值,C prog
- c - C lang 指数长双输出(Mac OS,Xcode)
- python - Ansible trim/regex_replace 得到错误输出
- machine-learning - 异常检测和异常值差异
- eclipse-plugin - 向导创建的 Xtext 和更新项目
- drools - 我需要使用 Kie 文件系统为动态生成的 DRL 文件实施 Drool Fluent API 的帮助
- shell - 将列与多个可能的值匹配
- javascript - Reactjs,在 componentWillUnmount 上移除事件监听器,
- python - 大列表的最大递归