首页 > 解决方案 > “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 大小写来公开带有驼峰大小写属性的路由?

标签: c#asp.net-coreasp.net-core-webapiasp.net-core-2.1

解决方案


好吧,你在某种程度上是正确的。这个:

[HttpGet("postcode/{postcode}/street/{street}")]

说你有一个postcode和一个street属性,而你一个都没有。如果您希望默认绑定起作用,则大小写必须完全匹配:

[HttpGet("postcode/{Postcode}/street/{Street}")]

推荐阅读