【问题标题】:ASP.NET web api mapping model with application/x-www-form-urlencoded HTTP POST带有 application/x-www-form-urlencoded HTTP POST 的 ASP.NET Web api 映射模型
【发布时间】:2019-12-10 20:28:45
【问题描述】:

我试图在 ASP.net WebAPI 中读取表单 url 编码的正文。 如果表单变量和我的模型变量名称相同(不区分大小写),则映射是直接的,但如果名称不同,则映射失败。

例如,

POST /api/values HTTP/1.1
Host: localhost:62798
Accept: text/json
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 51ee1c5f-acbb-335b-35d9-d2b8e62abc74

uid=200&email=john%40jones.com&first_name=John&last_name=jones&phone=433-394-3324&city=Seattle&state_code=WA&zip=98105


public class SampleModel{
    public string UID { get; set; }    
    public string Email { get; set; }    
    public string FirstName { get; set; }    
    public string LastName { get; set; }    
    public string Phone { get; set; }    
    public string City { get; set; }    
    public string StateCode { get; set; }    
    public string Zip { get; set; }
}

注意名字、姓氏和状态码变量。如果模式有first_name,它将被正确映射。但是如果你想遵守 C# 命名约定,我们需要将first_name 映射到FirstName

我知道如果它是 json,我可以很容易地将它映射到 JSON 属性名称,但是如何使用 urlencoded 表单数据来完成呢?

参考:ASP.net WebAPI Mapping with URL Encoded form

【问题讨论】:

    标签: c# asp.net-web-api x-www-form-urlencoded


    【解决方案1】:

    您应该在属性定义中使用绑定Attribute 来分配替代名称,如下所示:

    public class SampleModel{
        public string UID { get; set; }    
        public string Email { get; set; }    
    
        [FromForm(Name = "first_name")]
        public string FirstName { get; set; }
    
        [FromForm(Name = "last_name")]
        public string LastName { get; set; }    
        public string Phone { get; set; }    
        public string City { get; set; }    
    
        [FromForm(Name = "state_code")]
        public string StateCode { get; set; }    
        public string Zip { get; set; }
    }
    

    请注意,对于form-urlencoded,您应该在参数之前使用[FromForm] 属性:[FromForm]string stateCode

    【讨论】:

      猜你喜欢
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 2014-03-30
      相关资源
      最近更新 更多