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
662 views
in Technique[技术] by (71.8m points)

c# - WebAPI Selfhost: Can't bind multiple parameters to the request's content

The below code are simplified to show the necessity. May I know what is wrong? I can't seems to retrieve two Parameters (A and B in this case) using the [FromBody] attribute.

The error message is "Can't bind multiple parameters ('A' and 'B') to the request's content"

It is perfectly fine if I have either A or B only.

Web API:

[Route("API/Test"), HttpPost]
public IHttpActionResult Test([FromBody] int A, [FromBody] int B)

Client:

HttpClient client = new HttpClient();
var content = new FormUrlEncodedContent(
    new Dictionary<string, string> {
        { "A", "123" },
        { "B", "456" }
    });
client.PostAsync("http://localhost/API/Test", content).Result;
question from:https://stackoverflow.com/questions/38715230/webapi-selfhost-cant-bind-multiple-parameters-to-the-requests-content

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

1 Reply

0 votes
by (71.8m points)

Web Api doesn't support multiple [FromBody] params I think. But you can use Api model, to passing more parameters to your api action.:

public class YourApiModel
{
    public int A{ get; set; }

    public int B { get; set; }

    //...other properties    
}

After that, you can simply use this in your API controller Test:

    // POST: api/test
    public IHttpActionResult Post([FromBody] YourApiModel model)
    {
        //do something
    }

Hope it help.


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

...