简体   繁体   中英

Bind properties FromForm .NET Core Web API

I have .NET Core Web API project. One of my action controller is:

[HttpPost]
public async Task<IActionResult> Notify([FromForm] NotifyInput input)
{ ... }

NotifyInput.cs file is in separate project (.NET Standard):

public string BodyPlain { get; set; }

public string BodyHtml { get; set; }

public List<Attachment> Attachments { get; set; }

public class Attachment
{
    public int Size { get; set; }

    public string Url { get; set; }

    public string Name { get; set; }

    public string ContentType { get; set; }
}

And params I send to this method are:

body-plain: 123
body-html: <p>123</p>
attachments: [{"url": "http://example.com", "content-type": "image/jpeg", "name": "pexels-photo.jpg", "size": 62169}]

I'm trying to send my data via Postman as x-www-form-urlencoded and as form-data .

But when I debug this code, I see they are all NULL .

Attribute [JsonProperty("body-plain")] didn't help me.

How can I bind these params?

Try to use [ModelBinder(Name="name")] to specify a name for binding data

public class NotifyInput
{
    [ModelBinder(Name = "body-plain")]
    public string BodyPlain { get; set; }
    [ModelBinder(Name = "body-html")]
    public string BodyHtml { get; set; }

    public List<Attachment> Attachments { get; set; }
}
public class Attachment
{
    public int Size { get; set; }

    public string Url { get; set; }

    public string Name { get; set; }

    [ModelBinder(Name = "content-type")]
    public string ContentType { get; set; }

}

I played around with this and discovered that because you're passing a x-www-form-urlencoded to the endpoint, setting [JsonProperty("body-plain")] won't work; because you aren't sending Json.

So to pass those values you have to use the exact names on the models (case insensitive, but no hyphens). So, passing the following

bodyplain:123
bodyhtml:<p>123</p>

should work. attachments[0].content-type also has to become attachments[0].ContentType

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