首页 > 解决方案 > Angular 6 Post body 与请求对象内的数组到 Web API

问题描述

我想将数据从 angular post 传递到 web api。但在 web api 中它显示为空。

我的意图是通过 POST 请求将对象内部的列表传递给 Web Api。

Angular 服务 POST 方法:

postData(URL : string,body : any) : Observable<any> {     
var dto = {sortcolumn:"CustomerName", sortorder:"asc", pagenumber:"0",pagesize: "10"
          ,ddlUnits: [{"Value": "20022", "Text": "Arvind"},{"Value": "20022", "Text": "Arvind"}]
          };             
let bodystr = JSON.stringify(dto);

const httpOptions = {
  headers: new HttpHeaders({
    //'Content-Type':  'application/x-www-form-urlencoded',        
    'Content-Type':  'application/json',        
  })
};

return this._http.post<any>(this.BaseURL + URL, bodystr,httpOptions)

// 当我调用这个服务方法时,我会在组件中订阅它。

}

WEB API 动作方法:

 [Route("api/AllCustomers")]
    [HttpPost]
    public IHttpActionResult GetAllCustomerPOST([FromBody] CustomerDTO dto)
    {            
        try
        {
            List<GetAllCustomer_Result> lst = clsDCustomer.GetAllCustomer().ToList();               
            return new CustomResponseResult(HttpStatusCode.OK, Request, lst);
        }
        catch
        {
            return new CustomResponseResult(HttpStatusCode.InternalServerError, Request, Constants.MSGInternamServerError);
        }
    }

CLASS 结构(在动作请求中传递)

public class CustomerDTO 
{
    public long ID { get; set; }

    [Required(ErrorMessage = "Required")]
    [Display(Name = "Customer Name")]
    public string CustomerName { get; set; }

    [Required(ErrorMessage = "Required")]
    [MaxLength(length: 10, ErrorMessage = "Maximun length for mobile no is 10 digit")]
    [Display(Name = "Mobile No")]
    public string MobileNo { get; set; }

    [Display(Name = "Contact No")]
    public string ContactNo { get; set; }

    [Display(Name = "Address")]
    public string Address { get; set; }

    public int CreatedBy { get; set; }
    public System.DateTime CreatedOn { get; set; }

    public List<DropDownList> ddlUnits { get; set; }

    public int pagenumber { get; set; }
    public int pagesize { get; set; }
    public string sortcolumn { get; set; }
    public string sortorder { get; set; }
}   
public class DropDownList
{
    public string Value { get; set; }
    public string Text { get; set; }
}

我已经在 HttpParams() 中使用 'Content-Type':'application/x-www-form-urlencoded' 标头传递了正文数据并且可以工作,但无法在 WEB API 中获取 ddlUnits 属性。

我用原始的 Body json 用谷歌的 POST MAN 进行了测试。

{"sortcolumn":"CustomerName", "sortorder":"asc", "pagenumber":"0", "pagesize": "10","ddlUnits":[{"Value": "20022", "Text" : "Arvind"},{"Value": "20022", "Text": "Arvind"}]}

它工作正常

请参阅 检查元素网络错误屏幕截图

标签: angular

解决方案


由于属性名称的大小写,您很可能遇到问题。默认情况下,从 JSON 转换为 c# 时,小写属性名称会更改为大写首字母,因此如果您将 sortorder、sortcolumn、ddlUnits 等更改为具有大写首字母,它可能会起作用(前提是您将数据作为 application/json 内容传递类型)


推荐阅读