【问题标题】:using jsonData as a key value to send mixed data in asp: Does not update the database with the values在asp中使用jsonData作为键值发送混合数据:不使用值更新数据库
【发布时间】:2021-09-30 12:51:44
【问题描述】:

在尝试在邮递员中混合文件上传和 json 数据后,我终于找到了一种可以在同一个请求中发送它们的方法。因此,我将我的 json 数据移动到 Postman 中的 Key 中,这样就可以使用 form-data 发送文件(下图)。

在值内我有如下 JSON 数据:

{
   "WorkshopEmail":"workshopemail",
   "WorkshopContactperson":"workshopcontactperson",
   "WorkshopCellphone":"workshopcellphone",
   "Service":[
      {
         "service":"Claim Airbag",
         "RequestTypeId":"1",
         "DamageDate":"2021-05-03",
         "DamageKilometerreading":"213",
         "LatestServiceDate":"2021-05-03",
         "LatestServiceKilometer":"1223",
         "WorkshopDiagnos":"diagnos workshop",
         "CarOwnerDescription":"carownerdescription",
         "CategoryId":"25",
         "works":[
            {
               "title":"arbete 1 airbag",
               "chargePerHour":"11",
               "hours":"12",
               "price":"132.00",
               "id":"13926"
            },
            {
               "title":"arbete2 airbag",
               "chargePerHour":"1",
               "hours":"2",
               "price":"2.00",
               "id":"13927"
            },
            {
               "title":"part1 airbag",
               "pricePerUnit":"100",
               "quantity":"1",
               "price":"100.00",
               "id":"13928"
            },
            {
               "title":"part2 airbag",
               "pricePerUnit":"100",
               "quantity":"2",
               "price":"200.00",
               "id":"13929"
            }
         ]
      },
      {},
      {},
      {},
      {},
      {}
   ]
}

空的 {} 只包含更多的服务类型。现在,当我在 Postman 中发送请求时,我得到了 200 OK,当我调试时,我可以看到以下内容(抱歉,如果图片模糊):

¨ 但是,我的数据库没有使用这些值进行更新。下面是向表中插入数据的类:

public async Task<bool> AddRequest(Request model, List<IFormFile> file, [FromForm] string jsonData)
{
    bool CreateRequest = true;
    int requestID = 0;
    int claimID = 0;
    //bool country = true;

    //First Create the Request
    foreach (Service item in model.Service) 
    {
        //First Create the Request
        if (CreateRequest)
        {

            var parameters = new DynamicParameters();
            parameters.Add("WorkshopEmail", model.WorkshopEmail);
            parameters.Add("WorkshopContactperson", model.WorkshopContactperson);
            parameters.Add("WorkshopCellphone", model.WorkshopCellphone);
            parameters.Add("DamageDate", model.DamageDate);
            parameters.Add("LatestServiceDate", model.LatestServiceDate);
            parameters.Add("LatestServiceKilometer", model.LatestServiceKilometer);
            parameters.Add("DamageKilometerreading", model.DamageKilometerreading);
            parameters.Add("CurrentKilometerreading", model.CurrentKilometerreading);
            parameters.Add("CarOwnerDescription", model.CarOwnerDescription);
            parameters.Add("WorkshopDiagnos", model.WorkshopDiagnos);
            parameters.Add("AmountIncVat", model.AmountIncVat);



            try
            { 
            var requestIDenum = await _sqlconnection.QueryAsync<int>($@"INSERT INTO [dbo].[Request]
                                                    (WorkshopEmail,WorkshopContactperson,WorkshopCellphone,DamageDate,LatestServiceDate,
                                                     LatestServiceKilometer,DamageKilometerreading,CurrentKilometerreading,
                                                     CarOwnerDescription,WorkshopDiagnos,AmountIncVat)
                                                    VALUES
                                                    (@WorkshopEmail,@WorkshopContactperson,@WorkshopCellphone,@DamageDate,@LatestServiceDate,
                                                     @LatestServiceKilometer,@DamageKilometerreading,@CurrentKilometerreading,
                                                     @CarOwnerDescription,@WorkshopDiagnos,@AmountIncVat);SELECT SCOPE_IDENTITY();",parameters);
            requestID = requestIDenum.First();
            CreateRequest = false;

            }
            catch(Exception ex)
            {

                int hej = 0;
            }
        }
        
        if (item.fileuploadresults != null)
        {
            foreach (FileUploadResult f in item.fileuploadresults)
            {
                var parameters = new DynamicParameters();

                parameters.Add("file", f.filename);

                var filemessage = await _sqlconnection.QueryAsync<int>($@"INSERT INTO [dbo].[OptionalFile] ([FileName])
                                                  VALUES (@file); SELECT SCOPE_IDENTITY();", parameters);



                int FileMessageID = filemessage.First(); 

                
                await _sqlconnection.QueryAsync<int>($@"INSERT INTO[dbo].[ClaimCrossOptionalFile]
                                                    (ClaimID,FileID)
                                                    VALUES
                                                    ({claimID},{FileMessageID});");
            }
        }
              

    return true;
    //return list;
}      

控制器:

 [HttpPost]
        public async Task<IActionResult> AddRequest(List<IFormFile> file, [FromForm] string jsonData)
        {
            // if (!ModelState.IsValid)
            // {

            Request request = JsonConvert.DeserializeObject<Request>(jsonData); 

            try
            {
                //await _request.AddRequest(request);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }

            return Ok(); 
        }

界面:

Task<bool> AddRequest(Request model, List<IFormFile> file, [FromForm] string jsonData);

旁注:这是代码的一部分,因为我试图保持简短,所以这里可能缺少一些 } 或某些东西,但没有问题。如果我应该添加整个代码,我也许可以通过链接或类似的方式发送它,因为在这里上传会很多。

但是,我现在不知道如何处理这个问题。我以前很少使用表单数据,至少没有将 json 作为值传递。也许我在控制器中缺少/必须使用 json 数据做一些事情?我试过寻找解决方案,但我被困在这里。唯一的问题是数据库没有更新。

更新,模型:

 public class Work
    {
        //base for claim
        public string title { get; set; } = "";
        public string chargePerHour { get; set; } = "";
        public string hours { get; set; } = "";
        public string price { get; set; } = "";
        public string id { get; set; } = "";
        public string pricePerUnit { get; set; } = "";
        public string quantity { get; set; } = "";

        //service
        public int rentreasonId { get; set; } = -1;
        public int rentservicecartypeId { get; set; } = -1;

        //tyres
        public int tireserviceId { get; set; } = -1;

        public IList<TireType> tireTypes { get; set; }
        public IList<Labour> labours { get; set; }
        
        public DateTime DateFrom{ get; set; } = DateTime.Parse("1753-01-01");
        public DateTime DateTo { get; set; } = DateTime.Parse("1753-01-01");

        //Insurance
        public string totalAmount { get; set; }
        public string requestInsuranceVatID { get; set; }
        public string vat { get; set; } = "0.0";
        public string totalExclVat { get; set; }="0.0";
        public string totalIncVat { get; set; }="0.0";


    }

    public class Labour
    {
        public string title { get; set; } = "";
        public string chargePerHour { get; set; } = "";
        public string hours { get; set; } = "";

        public string price { get; set; } = "";
    }

    public class TireType
    {
        public string quantity { get; set; } = "";
        public string brand { get; set; } = "";
        public string model { get; set; } = "";

        public string pricePerUnit { get; set; } = "";
        public string price { get; set; } = "";

        public string tireTypeId { get; set; } = "";

        public string widthID { get; set; } = ""; 

        public string heightID { get; set; } = "";

        public string diameterID { get; set; } = "";
    }

    public class Request
    {
        public string WorkshopEmail { get; set; } = "";

        public string WorkshopContactperson { get; set; } = "";

        public string WorkshopCellphone { get; set; } = "";

        public int AmountIncVat { get; set; } = 0;

        #region Claim
        public DateTime DamageDate { get; set; } = DateTime.Parse("1753-01-01");

        public DateTime LatestServiceDate { get; set; } = DateTime.Parse("1753-01-01");

        public int LatestServiceKilometer { get; set; } = 0;

        public int DamageKilometerreading { get; set; } = 0;

        public int CurrentKilometerreading { get; set; } = 0;

        public string CarOwnerDescription { get; set; } = "";

        public string WorkshopDiagnos { get; set; } = "";

        //public string OptionalMessage { get; set; } = "";

        #endregion
        public IList<Service> Service { get; set; }

       
    }

    public class TireTread
    {
        public string tireserviceId { get; set; } = "";
        public string leftfront { get; set; } = "";
        public string rightfront { get; set; } = "";
        public string leftrear { get; set; } = "";
        public string rightrear { get; set; } = "";
        public string added1 { get; set; } = "";
        public string added2 { get; set; } = "";
        public string added3 { get; set; } = "";
        public string added4 { get; set; } = "";
        public string added5 { get; set; } = "";
    }

    public class TireMessage
    {
        public int tireserviceId { get; set; }
        public string message { get; set; }
    }

    public class Service
    {
     //   [JsonProperty("ServiceId")]
        public string RequestTypeId { get; set; } = "";
        public string CategoryId { get; set; } = "-1";
     
  

        public string OptionalMessage { get; set; } = "";

        public IList<Work> works { get; set; }
        public IList<TireTread> treads { get; set; }

        public IList<TireMessage> TireMessages { get; set; }

        //filuppladdning
        public IList<FileUploadResult> fileuploadresults { get; set; }
    }

    //filuppladdning
    public class FileUploadResult
    {
        //public IFormFile files { get; set; } 

        public string filename { get; set; }
    }

【问题讨论】:

  • 也许可以为您的 RequestModel 提供代码(我建议您考虑一个不同的名称,这非常通用)。调试时 Service 属性还有什么值?
  • @Sascha 我更新了。当我调试时,我可以看到整个 json 请求作为值传​​递
  • 调试的时候Request modelparameters有值吗?
  • 为什么不在 ASP.NET Core 方法中使用 RequestModel 作为类型?
  • @YiyiYou 不行,我只能看到json字符串..

标签: c# json asp.net-core postman dapper


【解决方案1】:

首先,json格式与模型结构不匹配,需要这样传递json(注意DamageKilometerreadingLatestServiceKilometer,它们的类型都是int,所以不要使用"") :

{
   "WorkshopEmail":"workshopemail",
   "WorkshopContactperson":"workshopcontactperson",
   "WorkshopCellphone":"workshopcellphone",
   "DamageDate":"2021-05-03",
   "DamageKilometerreading":213,
   "LatestServiceDate":"2021-05-03",
   "LatestServiceKilometer":1223,
   "WorkshopDiagnos":"diagnos workshop",
   "CarOwnerDescription":"carownerdescription",
   "Service":[
      {
         "service":"Claim Airbag",
         "RequestTypeId":"1",
         "CategoryId":"25",
         "works":[
            {
               "title":"arbete 1 airbag",
               "chargePerHour":"11",
               "hours":"12",
               "price":"132.00",
               "id":"13926"
            },
            {
               "title":"arbete2 airbag",
               "chargePerHour":"1",
               "hours":"2",
               "price":"2.00",
               "id":"13927"
            },
            {
               "title":"part1 airbag",
               "pricePerUnit":"100",
               "quantity":"1",
               "price":"100.00",
               "id":"13928"
            },
            {
               "title":"part2 airbag",
               "pricePerUnit":"100",
               "quantity":"2",
               "price":"200.00",
               "id":"13929"
            }
         ]
      },
      {},
      {},
      {},
      {},
      {}
   ]
}

然后尝试在服务模型中添加public string service { get; set; }=""

【讨论】:

    【解决方案2】:

    我找到了解决方案,以防其他人遇到此问题。我需要修改控制器并添加以下代码:

     [HttpPost]
            public async Task<IActionResult> AddRequest(List<IFormFile> file, [FromForm] string jsonData)
            {
                Request request = JsonConvert.DeserializeObject<Request>(jsonData);
    
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
                try
                {
                    await _request.AddRequest(request, file, jsonData);
    
                }
                catch (Exception ex)
                {
    
                    return BadRequest(ex.Message);
                }
    
                return Ok();
            }
    

    基本上添加request(我在方法的开头反序列化),并在等待请求中添加filejsonData,解决了这个问题。至于文件上传,我也需要修改该方法,将文件名放入数据库:

    if (file != null)
                    {
    
                        foreach (IFormFile f in file)
                        {
                            string filename = Path.GetFileName(f.FileName);
                            var parameters = new DynamicParameters();
                            parameters.Add("file", filename);
    
                            var filemessage = await _sqlconnection.QueryAsync<int>($@"INSERT INTO 
                            [dbo].[OptionalFile] ([FileName])
                            VALUES (@file); SELECT SCOPE_IDENTITY();", parameters);
        
                        }
                    
                    } 
    

    将这些更改为可以在同一请求中发送包含 json 键值和多个文件的请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-01
      • 2020-08-20
      • 2015-09-21
      • 1970-01-01
      • 2012-02-08
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多