【发布时间】:2018-08-31 06:36:13
【问题描述】:
在我的 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 大小写来公开带有驼峰大小写属性的路由?
【问题讨论】:
标签: c# asp.net-core asp.net-core-webapi asp.net-core-2.1