0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ASP.NET Web APIの自動デシリアライズでInternal Server Error(500)

0
Posted at

現象

クライアントからASP.NetのWebApiを呼び出した際に、自動でパラメータがデシリアライズされるが、
あるデータクラスで受け取ろうとした場合に、HttpStatusCode:500を吹いてエラーになる。

***Controller.cs
        [HttpPost()]
        public async Task<ActionResult> Post(Photo photo)
        {
            return Ok();
        }
Photo.cs
    public class Photo{
        public string name{get;set;}
        public string src{get;set;}

        public Photo(string name, string src){
            this.name = name;
            this.src = src;
        }
    }
送りつけてるデータ
    { name: "aaa", src: "ccc"}
エラー内容
System.NotSupportedException: Deserialization of reference types without parameterless constructor is not supported. Type '*****.Models.Photo'
   at System.Text.Json.ThrowHelper.ThrowNotSupportedException_DeserializeCreateObjectDelegateIsNull(Type invalidType)

原因

デシリアライズ時に引数無しのコンストラクタが無いため、エラーとなっていた。
そりゃそうか。。。

Photo.cs
    public class Photo{
        public string name{get;set;}
        public string src{get;set;}

        public Photo(){}

        public Photo(string name, string src){
            this.name = name;
            this.src = src;
        }
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?