简体   繁体   中英

Problems with FromFormAttribute and deserialization in AspNet Core 3.1 Api

I use Newtonsoft deserializer and try to send data(with FromFormAttribute) in this method:

[HttpPut("test")]
public IActionResult Test([FromForm] MyClass Test) {           
    return Ok();
}

also, I have class:

public class MyClass
{
    public int Id { get; protected set; }
    public string Text { get; protected set; }

    public MyClass(int id, string text) {
        Id = id;
        Text = text;
    }
}

When I try to send data in HttpPut method I get

System.InvalidOperationException: Could not create an instance of type 'MyClass'. 
Model bound complex types must not be abstract or value types and must have a parameterless constructor.
Alternatively, give the 'test' parameter a non-null default value.

I didn't create a parameterless constructor and have protected setters because it works fine in other methods with FromBodyAttribute.
What am I doing wrong?

just add a parameterless constructor

 public class MyClass
        {
            public int Id { get; set; }
            public string Text { get; set; }
            

            public MyClass()
            {
            }
            public MyClass(int id, string text)
            {
                Id = id;
                Text = text;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM