【问题标题】:Value cannot be null. (Parameter 'key') On Web API POST Method值不能为空。 (参数 'key')在 Web API POST 方法上
【发布时间】:2022-01-08 02:47:16
【问题描述】:

所以基本上我已经在 CarsRepository.cs 中创建了 Add Cars 方法

   public int AddCar(Car car)
        {
            _carRentalSystemContext.Cars.Add(car);
            _carRentalSystemContext.SaveChanges();
            return 1;
        }

在 CarsService.cs 中

   public int AddCar(Car car)
        {
           return _icarsRepository.AddCar(car); 
        }

在 ICarsRepository 和 ICarsServices 中

int AddCar(Car car);

CarsController 中的 Action 为

 [HttpPost]
        [Route("AddCar")]
        public IActionResult AddCar(Car car)
        {
            return new ObjectResult(_icarsService.AddCar(car));
        }

我的汽车模型类是

using System;
using System.Collections.Generic;


#nullable disable

namespace CAR_RENTAL_SYSTEM.Models
{
    public partial class Car
    {
        public Car()
        {
            Bookings = new HashSet<Booking>();
            CarReviews = new HashSet<CarReview>();
            DriverReviews = new HashSet<DriverReview>();
        }
        
        public int CarId { get; set; }
        public string CarModel { get; set; }
        public string CarRtoNumber { get; set; }
        public string CarType { get; set; }
        public decimal? CarMileage { get; set; }
        public int? CarPersonCapacity { get; set; }
        public string CarCondition { get; set; }
        public decimal? KmDone { get; set; }
        public string FuelType { get; set; }
        public decimal? RentPerKm { get; set; }
        public string ReviewId { get; set; }
        public string InService { get; set; }

        public virtual ICollection<Booking> Bookings { get; set; }
        public virtual ICollection<CarReview> CarReviews { get; set; }
        public virtual ICollection<DriverReview> DriverReviews { get; set; }
    }
}

我通过 Swagger 发送的 JSON 正文是

{
  "carId": 0,
  "carModel": "Audi",
  "carRtoNumber": "MHJK5645",
  "carType": "Sedan",
  "carMileage": 12,
  "carPersonCapacity": 8,
  "carCondition": "Good",
  "kmDone": 15500,
  "fuelType": "Petrol",
  "rentPerKm": 25,
  "reviewId": "MHJK12",
  "inService": "Yes",
  "bookings": [
    {
      "bookingId": 0,
      "customerId": 0,
      "carId": 0,
      "driverId": 0,
      "fromDate": "2022-01-07T14:32:48.971Z",
      "toDate": "2022-01-07T14:32:48.971Z",
      "fromLocation": "string",
      "toLocation": "string",
      "noOfPersons": 0,
      "bookingStatus": "string",
      "journeyCompletion": "string",
      "paymentStatus": "string",
      "createdOn": "2022-01-07T14:32:48.971Z",
      "updatedOn": "2022-01-07T14:32:48.971Z",
      "customer": {
        "customerId": 0,
        "customerName": "string",
        "customerPassword": "string",
        "customerEmail": "string",
        "customerPhone": "string",
        "customerAdress": "string",
        "customerCity": "string",
        "customerPin": 0,
        "createdOn": "2022-01-07T14:32:48.971Z",
        "updatedOn": "2022-01-07T14:32:48.971Z",
        "isActive": "string",
        "bookings": [
          null
        ],
        "carReviews": [
          null
        ],
        "driverReviews": [
          null
        ],
        "feedbacks": [
          {
            "feedbackId": 0,
            "bookingId": 0,
            "customerId": 0,
            "feedbackMsg": "string"
          }
        ]
      },
      "driver": {
        "driverId": 0,
        "driverName": "string",
        "driverLicensenumber": "string",
        "driverEmail": "string",
        "driverPassword": "string",
        "driverPhone": "string",
        "driverAddress": "string",
        "anyAddiction": "string",
        "driverAge": 0,
        "reviewId": "string",
        "inService": "string",
        "isActive": "string",
        "bookings": [
          null
        ],
        "driverReviews": [
          null
        ],
        "journeyCompletions": [
          {
            "journeyId": 0,
            "bookingId": 0,
            "driverId": 0,
            "kmDone": 0,
            "totalFare": 0,
            "receipts": [
              {
                "receiptId": 0,
                "bookingId": 0,
                "journeyId": 0,
                "totalFare": 0,
                "paymentStatus": "string"
              }
            ]
          }
        ]
      },
      "carReviews": [
        {
          "reviewId": 0,
          "carId": 0,
          "customerId": 0,
          "bookingId": 0,
          "review": "string",
          "rating": 0,
          "customer": {
            "customerId": 0,
            "customerName": "string",
            "customerPassword": "string",
            "customerEmail": "string",
            "customerPhone": "string",
            "customerAdress": "string",
            "customerCity": "string",
            "customerPin": 0,
            "createdOn": "2022-01-07T14:32:48.972Z",
            "updatedOn": "2022-01-07T14:32:48.972Z",
            "isActive": "string",
            "bookings": [
              null
            ],
            "carReviews": [
              null
            ],
            "driverReviews": [
              null
            ],
            "feedbacks": [
              {
                "feedbackId": 0,
                "bookingId": 0,
                "customerId": 0,
                "feedbackMsg": "string"
              }
            ]
          }
        }
      ],
      "driverReviews": [
        {
          "reviewId": 0,
          "driverId": 0,
          "customerId": 0,
          "carId": 0,
          "bookingId": 0,
          "review": "string",
          "rating": 0,
          "customer": {
            "customerId": 0,
            "customerName": "string",
            "customerPassword": "string",
            "customerEmail": "string",
            "customerPhone": "string",
            "customerAdress": "string",
            "customerCity": "string",
            "customerPin": 0,
            "createdOn": "2022-01-07T14:32:48.972Z",
            "updatedOn": "2022-01-07T14:32:48.972Z",
            "isActive": "string",
            "bookings": [
              null
            ],
            "carReviews": [
              null
            ],
            "driverReviews": [
              null
            ],
            "feedbacks": [
              {
                "feedbackId": 0,
                "bookingId": 0,
                "customerId": 0,
                "feedbackMsg": "string"
              }
            ]
          },
          "driver": {
            "driverId": 0,
            "driverName": "string",
            "driverLicensenumber": "string",
            "driverEmail": "string",
            "driverPassword": "string",
            "driverPhone": "string",
            "driverAddress": "string",
            "anyAddiction": "string",
            "driverAge": 0,
            "reviewId": "string",
            "inService": "string",
            "isActive": "string",
            "bookings": [
              null
            ],
            "driverReviews": [
              null
            ],
            "journeyCompletions": [
              {
                "journeyId": 0,
                "bookingId": 0,
                "driverId": 0,
                "kmDone": 0,
                "totalFare": 0,
                "receipts": [
                  {
                    "receiptId": 0,
                    "bookingId": 0,
                    "journeyId": 0,
                    "totalFare": 0,
                    "paymentStatus": "string"
                  }
                ]
              }
            ]
          }
        }
      ],
      "feedbacks": [
        {
          "feedbackId": 0,
          "bookingId": 0,
          "customerId": 0,
          "feedbackMsg": "string"
        }
      ],
      "journeyCompletions": [
        {
          "journeyId": 0,
          "bookingId": 0,
          "driverId": 0,
          "kmDone": 0,
          "totalFare": 0,
          "receipts": [
            {
              "receiptId": 0,
              "bookingId": 0,
              "journeyId": 0,
              "totalFare": 0,
              "paymentStatus": "string"
            }
          ]
        }
      ],
      "receipts": [
        {
          "receiptId": 0,
          "bookingId": 0,
          "journeyId": 0,
          "totalFare": 0,
          "paymentStatus": "string"
        }
      ]
    }
  ],
  "carReviews": [
    {
      "reviewId": 0,
      "carId": 0,
      "customerId": 0,
      "bookingId": 0,
      "review": "string",
      "rating": 0,
      "customer": {
        "customerId": 0,
        "customerName": "string",
        "customerPassword": "string",
        "customerEmail": "string",
        "customerPhone": "string",
        "customerAdress": "string",
        "customerCity": "string",
        "customerPin": 0,
        "createdOn": "2022-01-07T14:32:48.972Z",
        "updatedOn": "2022-01-07T14:32:48.972Z",
        "isActive": "string",
        "bookings": [
          null
        ],
        "carReviews": [
          null
        ],
        "driverReviews": [
          null
        ],
        "feedbacks": [
          {
            "feedbackId": 0,
            "bookingId": 0,
            "customerId": 0,
            "feedbackMsg": "string"
          }
        ]
      }
    }
  ],
  "driverReviews": [
    {
      "reviewId": 0,
      "driverId": 0,
      "customerId": 0,
      "carId": 0,
      "bookingId": 0,
      "review": "string",
      "rating": 0,
      "customer": {
        "customerId": 0,
        "customerName": "string",
        "customerPassword": "string",
        "customerEmail": "string",
        "customerPhone": "string",
        "customerAdress": "string",
        "customerCity": "string",
        "customerPin": 0,
        "createdOn": "2022-01-07T14:32:48.972Z",
        "updatedOn": "2022-01-07T14:32:48.972Z",
        "isActive": "string",
        "bookings": [
          null
        ],
        "carReviews": [
          null
        ],
        "driverReviews": [
          null
        ],
        "feedbacks": [
          {
            "feedbackId": 0,
            "bookingId": 0,
            "customerId": 0,
            "feedbackMsg": "string"
          }
        ]
      },
      "driver": {
        "driverId": 0,
        "driverName": "string",
        "driverLicensenumber": "string",
        "driverEmail": "string",
        "driverPassword": "string",
        "driverPhone": "string",
        "driverAddress": "string",
        "anyAddiction": "string",
        "driverAge": 0,
        "reviewId": "string",
        "inService": "string",
        "isActive": "string",
        "bookings": [
          null
        ],
        "driverReviews": [
          null
        ],
        "journeyCompletions": [
          {
            "journeyId": 0,
            "bookingId": 0,
            "driverId": 0,
            "kmDone": 0,
            "totalFare": 0,
            "receipts": [
              {
                "receiptId": 0,
                "bookingId": 0,
                "journeyId": 0,
                "totalFare": 0,
                "paymentStatus": "string"
              }
            ]
          }
        ]
      }
    }
  ]
}

所以在构建这个项目之后,当我尝试使用相应的 JSON 主体添加汽车时,我得到了构建成功并且在发生以下错误时大摇大摆

System.ArgumentNullException: Value cannot be null. (Parameter 'key')
   at System.Collections.Generic.Dictionary`2.FindValue(TKey key)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityReferenceMap.TryGet(Object entity, IEntityType entityType, InternalEntityEntry& entry, Boolean throwOnNonUniqueness)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.TryGetEntry(Object entity, IEntityType entityType, Boolean throwOnTypeMismatch)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.InitialFixup(InternalEntityEntry entry, Boolean fromQuery)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.StateChanged(InternalEntityEntry entry, EntityState oldState, Boolean fromQuery)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.StateChanged(InternalEntityEntry entry, EntityState oldState, Boolean fromQuery)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.FireStateChanged(EntityState oldState)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1 node)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.SetEntityState(InternalEntityEntry entry, EntityState entityState)
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.Add(TEntity entity)
   at CAR_RENTAL_SYSTEM.Repositories.CarsRepository.AddCar(Car car) in C:\Users\Sarvesh\source\repos\CAR_RENTAL_SYSTEM\Repositories\CarsRepository.cs:line 15
   at CAR_RENTAL_SYSTEM.Services.CarsService.AddCar(Car car) in C:\Users\Sarvesh\source\repos\CAR_RENTAL_SYSTEM\Services\CarsService.cs:line 16
   at CAR_RENTAL_SYSTEM.Controllers.CarsController.AddCar(Car car) in C:\Users\Sarvesh\source\repos\CAR_RENTAL_SYSTEM\Controllers\CarsController.cs:line 22
   at lambda_method2(Closure , Object , Object[] )
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: close
Content-Length: 5075
Content-Type: application/json
Cookie: ai_user=05ZDd|2021-12-14T10:16:21.921Z; ai_session=zEAqz|1641560256601|1641562776408.5
Host: localhost:44353
Referer: https://localhost:44353/swagger/index.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Microsoft Edge";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
origin: https://localhost:44353
sec-fetch-site: same-origin
sec-fetch-mode: cors
sec-fetch-dest: empty

我检查了方法和模型,没有问题项目构建成功并且更新方法适用于同一模型但没有添加方法

如何解决这个错误?

注意:此项目是使用 DBFirst 和 Scaffold 命令创建的,用于生成模型。

【问题讨论】:

  • 你能把你发送给控制器的数据贴出来吗?
  • 是的,我将上传我通过 Swagger 发送的数据
  • @AchoVasilev 你能检查请求的代码吗,我已经添加了
  • 尝试删除 carId 并仅发送汽车数据,而不发送集合。只有carModel、carType等。
  • 谢谢@AchoVasilev,它一直在使用 Insomnia 作为带有 JSON 正文的 Rest 客户端,仅用于相应的表,而不像 Swagger 默认建议的那样

标签: c# .net asp.net-core asp.net-core-webapi


【解决方案1】:

更新:感谢 AchoVasilev,我从 Json Body 中删除了 Id,原样 数据库中的自动增量,以及由 Swagger 建议的请求正文默认引起的错误还包含对其他表的引用。

我做了什么: 我将 Insomnia 用作 Rest 客户端,并在没有 CarID [Which Was Identity] 的情况下使用 Json Body 调用相同的 API 端点并删除了其他表引用,结果为 :

{
  
  "carModel": "CarNameHere",
  "carRtoNumber": "DL456560",
  "carType": "Sedan",
  "carMileage": 18,
  "carPersonCapacity": 5,
  "carCondition": "Excellent",
  "kmDone": 15000,
  "fuelType": "Petrol",
  "rentPerKm": 20,
  "reviewId": "DL4565",
  "inService": "Yes"
  
 
}

并发送了 POST 请求,它工作得非常完美..

【讨论】:

    猜你喜欢
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 2014-01-28
    • 2015-08-07
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多