Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
99 views
in Technique[技术] by (71.8m points)

How to send enum property in a json to .net core 3.1 API?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found out why problem occurs, I've wrote User instead of UserCreateDto in this line:

public ActionResult<UserReadDto> CreateUser(**UserCreateDto ** userCreateDto)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...