Invalid for serialization or deserialization because it is a pointer type, is a ref struct, or contains generic parameters
В чем причина и как исправить ошибку:
System.InvalidOperationException: The type 'System.Threading.ExecutionContext&' of property 'Context' on type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Boolean,tinder_API.HttpConnection.RabbitMqConnection+<AddUser>d__4]' is invalid for serialization or deserialization because it is a pointer type, is a ref struct, or contains generic parameters that have not been replaced by specific types.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_CannotSerializeInvalidType(Type typeToConvert, Type declaringType, MemberInfo memberInfo)
at System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver.CreatePropertyInfo(JsonTypeInfo typeInfo, Type typeToConvert, MemberInfo memberInfo, JsonSerializerOptions options, Boolean shouldCheckForRequiredKeyword, Boolean hasJsonIncludeAttribute)
at System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver.AddMembersDeclaredBySuperType(JsonTypeInfo typeInfo, Type currentType, Boolean constructorHasSetsRequiredMembersAttribute, PropertyHierarchyResolutionState& state)
at System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver.PopulateProperties(JsonTypeInfo typeInfo)
at System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver.CreateTypeInfoCore(Type type, JsonConverter converter, JsonSerializerOptions options)
at System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver.GetTypeInfo(Type type, JsonSerializerOptions options)
at System.Text.Json.JsonSerializerOptions.GetTypeInfoNoCaching(Type type)
at System.Text.Json.JsonSerializerOptions.CachingContext.CreateCacheEntry(Type type, CachingContext context)
Код в котором отправляется post запрос к апи
public sealed class RabbitMqConnection
(
IHttpClientFactory httpClientFactory,
ILogger<HttpService> logger)
{
//https://localhost:7274 prooducer
//http://localhost:5147
private readonly string baseUrl = "http://localhost:7274";
private readonly static UserEndpoints userEndpoints;
public async Task<bool> AddUser(User user)
{
using HttpClient client = httpClientFactory.CreateClient();
client.BaseAddress = new Uri(baseUrl);
// создаем MultipartFormDataContent
using var content = new MultipartFormDataContent();
var json = JsonConvert.SerializeObject(user);
var userContent = new StringContent(json, Encoding.UTF8, "application/json");
userContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "info"
};
var response = await client.PostAsync(userEndpoints.RABBIT_MQ_AddUser, content);
return response.IsSuccessStatusCode;
}
}
Сам класс пользователя выглядит так (я не вижу здесь полей которые бы подходили под описание ошибки: is invalid for serialization or deserialization because it is a pointer type, is a ref struct, or contains generic parameters that have not been replaced by specific types.)
Код сервера
[HttpPost]
[Microsoft.AspNetCore.Mvc.Route("AddUser")]
public async Task<IActionResult> AddUser(User user) // public IActionResult AddUser(User user)
{
Debug.WriteLine($"Получен запрос на добавление пользователя");
Console.WriteLine($"Получен запрос на добавление пользователя");
// _mqService.AddUser(user);
return Ok("User send");
}
namespace Models
{
public enum Gender_type {
BOY, GIRL, NOONE
}
public class User /*: IdentityUser*/
{
[Key]
public Guid Id { get; set; }
public required string Name { get; set; }
public required string Surname { get; set; }
public required string Middlename { get; set; }
public required string Email { get; set; }
public required string Password { get; set; }
public Gender_type Gender { get; set; }
public string? Education { get; set; }
public string? Work { get; set; }
public string? Salary { get; set; }
public string? Hobby { get; set; }
public string? Goal { get; set; }
[Range(18,100)]
public required int Age { get; set; }
public int Height { get; set; }
public int Weight { get; set; }
public string Photo { get; set; }
}
}
Избавилась от ошибки заменив так:
[HttpPost]
[Microsoft.AspNetCore.Mvc.Route("AddUser")]
public async Task<IActionResult> AddUser(User user)
//Было public IActionResult AddUser(User user)
{
// dbApi.AddUser(user);
var response = await _rbtMQ.AddUser(user);
return Ok(response);
}
Но к сожалению все равно возникает исключение
System.Net.Http.HttpRequestException: An error occurred while sending the request.
---> System.Net.Http.HttpIOException: The response ended prematurely. (ResponseEnded)
at System.Net.Http.HttpConnection.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.HttpConnection.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.<SendCoreAsync>g__Core|5_0(HttpRequestMessage request, Boolean useAsync, CancellationToken cancellationToken)
at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.<SendCoreAsync>g__Core|5_0(HttpRequestMessage request, Boolean useAsync, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at tinder_API.HttpConnection.RabbitMqConnection.AddUser(User user) in C:\Users\katev\source\repos\Tinder\tinder-API\HttpConnection\RabbitMqConnection.cs:line 37
at tinderAPI.Controllers.UsersController.AddUser(User user) in C:\Users\katev\source\repos\Tinder\tinder-API\Controllers\UsersController.cs:line 39
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
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>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|20_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.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
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.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
Ответы (1 шт):
Автор решения: DerSkythe
→ Ссылка
Ваш код:
// создаем MultipartFormDataContent
using var content = new MultipartFormDataContent();
var json = JsonConvert.SerializeObject(user);
// Создаём userContent
var userContent = new StringContent(json, Encoding.UTF8, "application/json");
// Заполнили
userContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "info"
};
// И оставили userContent, не добавив в content, который отправляем
var response = await client.PostAsync(userEndpoints.RABBIT_MQ_AddUser, content);
А в целом, лучше использовать просто JSON, не вкладывая ни в какие контейнеры, также, рекомендую использовать System.Text.Json
вместо Newton