代码之家  ›  专栏  ›  技术社区  ›  SmartestVEGA

web api post数组但frombody始终为空

  •  0
  • SmartestVEGA  · 技术社区  · 6 年前

    我有以下格式的数组,需要将其发布到API:

    控制台日志(addserverlist);

    Array

    我想把这个传递给api的post方法

       const options = {headers: {'Content-Type': 'application/json'}};
                return this.http.post(           'http://localhost:54721/api/BulkUpload/SaveBulkUploadData',addserverList,options)
    

    我可以发布到api,但数据传递始终显示为空

    Null value

    模型I结构如下:

    model

    生成数组的函数

    private extractData(res: Response) {
    
            let csvData = res['_body'] || '';
            let allTextLines = csvData.split(/\r\n|\n/);
            let headers = allTextLines[0].split(',');
            let lines = [];
    
            for ( let i = 0; i < allTextLines.length; i++) {
                // split content based on comma
                let data = allTextLines[i].split(',');
                if (data.length == headers.length) {
                    let tarr = [];
                    for ( let j = 0; j < headers.length; j++) {
                        tarr.push(data[j]);
                    }
                    lines.push(tarr);
                }
            }
            this.csvData = lines;
    
           // console.log(JSON.stringify(this.csvData));
            this.saveBulkUpload();  
          }
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   SBFrancies    6 年前

    json是一个数组数组。该方法需要一个对象数组,该数组与 AddServer 上课。

    您的json应该如下所示:

    [
       {
            "HostName": "Server1", 
            "Type1": "type1_1", 
            "Type2": "type1_1", 
        },
        {
            "HostName": "Server2", 
            "Type1": "type1_2", 
            "Type2": "type2_2",  
        }
    ]
    

    更改为功能

    这需要一些猜测,因为我不知道传入函数的服务契约,但需要更改的是循环中的服务契约。

    for ( let i = 0; i < allTextLines.length; i++) {
            // split content based on comma
            let data = allTextLines[i].split(',');
    
            if (data.length == headers.length) {
                let tobj = {};
    
                tobj.HostName = data[0];
                tobj.Type1= data[1];
                tobj.Type2= data[2];
    
                lines.push(tobj);
            }
        }