【问题标题】:Custom Property name for FromUrl ModelFromUrl 模型的自定义属性名称
【发布时间】:2021-10-07 01:30:47
【问题描述】:

我有一个用于绑定 QueryString 的模型,它遵循 c# 的命名对话,但 QueryString 处于不同的命名对话中。如何为分配给 FromUrl 的模型属性提供自定义属性名称?

// Will NOT work
public class FormatDatabaseRequest
{
    [JsonProperty("_type")]
    public string Type { get; set; }

    [JsonProperty(Name = "awef_flag")]
    public string AwefFlag { get; set; }
}

// Controller.cs
[HttpPost]
public async Task<HttpResponseMessage> FormatDatabaseAsync([FromUri] FormatDatabaseRequest request) {}

// Sample URL (QueryString MUST be named _type and awef_flag)
// https://localhost:43521/myControllerName?_type=asdfa&awef_flag=asdf

【问题讨论】:

    标签: c# asp.net asp.net-web-api


    【解决方案1】:

    如果你想像这样从 URL 中获取字段,我建议使用 [FromQuery] 属性,如下所示:

    public async Task<HttpResponseMessage> Get([FromQuery] FormatDatabaseRequest data)
    

    那么,这样的网址

    https://localhost:43521/myControllerName?type=asdfa&awefflag=asdf
    

    将被正确解析为您的对象:)

    【讨论】:

    • 我需要myControllerName?_type=asdfa&amp;awef_flag=asdf 作为我的网址
    • 另外,FromQuery 是 AspNetCore 的一部分,我需要 AspNet
    【解决方案2】:

    json 与查询字符串无关。我不明白你为什么不喜欢下划线属性,但你可以像这样隐藏它们

    public class FormatBaseRequest
    {
        public string _Type { get; set; }
        public string Awef_flag{ get; set; }
    } 
    public class FormatDatabaseRequest:FormatBaseRequest
    {
       
        public string Type 
        { 
            get { return _Type; }
           set { _Type=value ; } //or leave just get
        }
    
       
        public string AwefFlag 
       { 
           get { return Awef_flag; }
           set { Awef_flag=value ; } //or leave just get
        }
    }
    

    您可以将它用于查询字符串和 c#

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-19
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多