【问题标题】:.NET Core Model Not Binding.NET Core 模型未绑定
【发布时间】:2019-07-10 02:30:39
【问题描述】:

我有一个接受模型实例的 .NET Core API POST 方法。我正在通过 Postman 测试我的 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

在 Postman 中,我像这样发送我的 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 的开发方式有点陌生,但我应该指定一些配置设置以使其正常工作还是需要其他东西?

【问题讨论】:

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


    【解决方案1】:

    布尔值是“真”或“假”

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

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

    【讨论】:

    • 还要注意json中的属性名称不能准确反映对象中的属性名称,例如对象中的“Puaddress1”,但 JSON 中的“address1”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    • 2019-06-15
    • 2021-06-30
    • 1970-01-01
    • 2020-03-23
    • 2022-01-06
    • 2018-08-22
    相关资源
    最近更新 更多