// Класс
public class Model
{
public string Name { get; set; }
public List<Item> Items { get; set; } = new List<Item>();
}
public class Item
{
public string Description { get; set; }
}
Это модель, о которой я говорил.
// Модель 1
{
"Name": "",
"Items":[
{
"Description":""
}
]
}
// Модель 2
{
"Name": ""
}
// Запрос
var model = new Model();
var content = JsonConvert.SerializeObject(model);
using var client = new HttpClient { "BaseAddress" = new Uri("http://localhost:80/main") };
var content = new StringContent(
content,
Encoding.UTF8,
"application/json");
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("insert", content);
// Контроллер
[ApiController]
public class MainController : ControllerBase
{
[HttpPost("insert")]
public async Task<IActionResult> Insert([FromBody] Model model)
{
}
}
Если я вставлю Модель 1 со списком, я получу
{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Date: Thu, 13 Feb 2020 22:04:06 GMT
Server: Kestrel
Transfer-Encoding: chunked
Content-Type: text/plain
}}
Но если я вставлю Модель 2 без списка, все будет работать нормально.
Я попытался передать список в виде строки json своему контроллеру вручную (отправка), и выполняет те же действия, не принимает список, но принимает модель.
Я получил исключение для API
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.NotSupportedException: Collection was of a fixed size.
at System.Array.System.Collections.IList.Add(Object value)
at System.Text.Json.JsonSerializer.ApplyObjectToEnumerable(Object value, ReadStack& state, Boolean setPropertyDirectly)
at System.Text.Json.JsonSerializer.HandleEndArray(JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
at System.Text.Json.JsonSerializer.ReadCore(JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan`1 buffer, JsonSerializerOptions options, ReadStack& readStack)
at System.Text.Json.JsonSerializer.ReadAsync[TValue](Stream utf8Json, Type returnType, JsonSerializerOptions options, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
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.<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 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)
Он не достигает контроллера, когда я ставлю точку останова.
Я нахожусь на netcoreapp3.1 Newtonsoft. Json 12.0.3 На него ссылаются в нестандартном проекте 2.1