Everything looks good but I don't understand why I still get an error like:
"System.InvalidCastException: The field of type DotnetCoreWebAPI.Enum+Blood must be a string, array or ICollection type."
I've left some meaningful snippets of code and the error I'm getting, below.
Model:
public class User
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
[MaxLength(100)]
public string Surname { get; set; }
[MaxLength(2)]
public Enum.Blood Blood { get; set; }
[MaxLength(50)]
public string Cellphone { get; set; }
[MaxLength(500)]
public string Adress { get; set; }
}
Enum:
public class Enum
{
public enum Blood
{
ARhDpositive,
ARhDnegative,
BRhDpositive,
BRhDnegative,
ORhDpositive,
ORhDnegative,
ABRhDpositive,
ABRhDnegative
}
}
Controller:
[HttpPost]
public ActionResult<UserReadDto> CreateUser(User userCreateDto)
{
var userModel = _mapper.Map<User>(userCreateDto);
_repository.CreateUser(userModel);
return Ok(userModel);
}
Service Configurations:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UserContext>(opt => opt.UseSqlServer
(Configuration.GetConnectionString("DatabaseConnection")));
services.AddControllers().AddJsonOptions(opt =>
opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddScoped<IUserRepo, SqlUserRepo>();
}
Note:
I use Postman when I test api
question from:
https://stackoverflow.com/questions/65868053/how-to-send-enum-property-in-a-json-to-net-core-3-1-api 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…