【问题标题】:How to pass multiple keys to array in ASP Web Api?如何在 ASP Web Api 中将多个键传递给数组?
【发布时间】:2021-01-04 15:12:27
【问题描述】:

我需要编写 ASP Web Api 代码,它将接受用户以这种格式输入:

"GenreName" : "Rock",
"Songs":[
"SongName":"Song 1",
"Length":233,
"Composer":"Composer 1"
],
[
"SongName":"Song 2",
"Length":221,
"Composer":"Composer 2"
]

这些值是通过 Postman 使用 JSON 发送的。我已经想出使用 string[] SongName 来添加歌曲列表,但是我需要传递其他键,以便可以填充 SQL 中的所有列,例如长度和作曲家。困扰我的事情是如何将所有这些值放入数组中,然后用 foreach 循环它们。以下是我到目前为止设法提出的代码:

  public void Execute(InsertDTO request)
        {
            var genre = request.GenreName;
            var datum = request.Datum;
            var trackname = request.TrackName;
            //var add = new Genre
            //{
            //    Name = genre
            //};

            //context.Genre.Add(add);

            //   int id = add.GenreId;


            var check = context.Genre.Where(x=>x.Name == request.GenreName).Count();

           // var chek2= context.Track.Where(x=>x.Name==request.Tracks.con)
         

                if (datum > DateTime.Now)
                {
                    throw new ArgumentException("datum ne moze biti u buducnosti");
                }
                else
                {

                    Genre g = new Genre
                    {
                        Name = genre,
                        Datum = datum

                    };

                    context.Genre.Add(g);

                    context.SaveChanges();

                var id = g.GenreId;

                foreach (var t in trackname) {

                    var pesma = t;

                    Track track = new Track
                    {
                        MediaTypeId=1,
                        GenreId = id,
                        Name=pesma
                    };

                    context.Track.Add(track);
                    context.SaveChanges();
                }

                }
            }

插入DTO.cs

public class InsertDTO
    {
       // public int GenreId { get; set; }
      
        public string GenreName { get; set; }

        public DateTime Datum { get; set; }

        public string[] TrackName { get; set; }
        
    }
}

非常感谢您的帮助!

【问题讨论】:

    标签: c# json asp.net-web-api postman


    【解决方案1】:

    由于您的代码示例未显示 API 调用,因此可能很难提供答案。根据我的经验,将您的 InsertDTO 模型转换为 JSON 字符串,然后将 JSON 字符串传递给 Web API 是正确的做法。

    Can i use JSON.Stringify in code-behind of an ASP.Net project

    var jsonStr = new JavaScriptSerializer().Serialize(myModel);
    

    【讨论】:

    • API 调用是什么意思?
    • 我需要关于如何遍历多个数组的逻辑。希望这是有道理的。
    • JavaScriptSerializer 不推荐使用
    猜你喜欢
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 2021-12-31
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多