.NET核心模型未绑定

时间:2019-07-09 14:26:56

标签: json asp.net-core asp.net-web-api

我有一个.NET Core API POST方法,该方法接受模型的实例。我正在通过邮递员测试我的API,当我将json格式的对象发送到我的api时,我在日志引用中看到了模型绑定。我认为模型绑定无法正常工作。这是邮递员的输出:

System.Text.Json.JsonException: The JSON value could not be converted to System.Boolean. Path: $.damaged | LineNumber: 0 | BytePositionInLine: 41.
   at System.Text.Json.ThrowHelper.ThowJsonException(String message, Utf8JsonReader& reader, String path)
   at System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType, Utf8JsonReader& reader, String path)
   at System.Text.Json.Serialization.JsonPropertyInfoNotNullable`3.Read(JsonTokenType tokenType, ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.Serialization.JsonSerializer.HandleValue(JsonTokenType tokenType, JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& state)
   at System.Text.Json.Serialization.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
   at System.Text.Json.Serialization.JsonSerializer.ReadCore(JsonReaderState& readerState, Boolean isFinalBlock, Span`1 buffer, JsonSerializerOptions options, ReadStack& readStack)
   at System.Text.Json.Serialization.JsonSerializer.ReadAsync[TValue](Stream utf8Json, Type returnType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
   at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext bindingContext)
   at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value)
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)
   at IdentityServer4.Hosting.MutualTlsTokenEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Cache-Control: no-cache
Connection: keep-alive
Content-Type: application/json
Accept: application/json
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Authorization: Bearer eyJhbGciOiJ...
Cookie: _ga=GA1.1.968351695.1527270246; __utma=111872281.968351695.1527270246.1529431622.1530048579.3
Host: localhost:5001
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
Origin: chrome-extension://coohjcphdfgbiolnekdpbcijmhambjff
Content-Length: 194

在邮递员中,我这样发送json:

{ "puDate": "0001-01-01", "damaged": "No", "boxed": "No", "pieceCount": 0, "address1": "123", "address2": "", "address3": "", "zip": "12345", "city": "SomeCity", "state": "AB", "po": 534560349, "createDate": "2019-06-06", "createdBy": "Me" }

我的WebAPI操作(默认支架)

// POST: api/ReturnShipmentQueues
        [HttpPost]
        public async Task<ActionResult<ReturnShipmentQueue>> PostReturnShipmentQueue(ReturnShipmentQueue returnShipmentQueue)
        {
            _context.ReturnShipmentQueue.Add(returnShipmentQueue);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (ReturnShipmentQueueExists(returnShipmentQueue.FkPonumber))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtAction("GetReturnShipmentQueue", new { id = returnShipmentQueue.FkPonumber }, returnShipmentQueue);
        }

当然还有模型:

using System;
using System.ComponentModel.DataAnnotations;

namespace WebApplication12.Models
{
    public partial class ReturnShipmentQueue
    {
        [Key]
        public long FkPonumber { get; set; }
        public DateTime PickupDate { get; set; }
        public bool Damaged { get; set; }
        public bool Boxed { get; set; }
        public int Pieces { get; set; }
        public string Puaddress1 { get; set; }
        public string Puaddress2 { get; set; }
        public string Puaddress3 { get; set; }
        public string Pucity { get; set; }
        public string Pustate { get; set; }
        public string Puzip { get; set; }
        public DateTime CreateDate { get; set; }
        public string CreatedBy { get; set; }
    }
}

我对API的开发方式有些陌生,但是我应该为此指定一些配置设置吗?还是我需要其他东西?

2 个答案:

答案 0 :(得分:2)

布尔值是'true'或'false'

您的示例中的“否”,请检查您的布尔字段

"damaged": "No"
"boxed": "No"

答案 1 :(得分:0)

1-将puDate更改为PickupDate

2-将“损坏”和“装箱”值更改为true或false

3-正确输入变量的所有名称

4-将双引号添加到字符串变量的第一个和最后一个值。 为“ Pustate”:“值”