ASP.NET Web API allows only one body parameter in POST

Posted on Leave a comment

Say with me, “ASP.NET Web API allows only one body parameter in POST”. And again, “ASP.NET Web API allows only one body parameter in POST”. Now repeat it 100 times.

It’s tiresome and probably utterly unnecessary. But that’s the only way to remember it. Believe me. I keep falling in the trap and repeating the same mistake over and over. I have wasted countless hours on this simple, stupid thing.

Don’t be like me. Memorize this mantra. Do it now. Do not delay it.

You know my pain if you have ever received this super-generic message and spent a gazillion fertile hours googling for a solution.

No action was found on the controller that matches the request

It’s like being told that your car cannot be driven because a part is missing. But, wait! Which part? Which f**k**g part? If you have been through this pain, you are my friend.

There could be countless reasons for this error. Perhaps you tried to access the wrong URL. Perhaps you used the wrong HTTP method. Perhaps you misspelled a parameter name.

Or, if you are like me, perhaps you had more than one parameter in a POST API method. Like this:

public async Task<HttpResponseMessage> AddProduct(int productId, string productName)
{
     ...
}

You were probably anticipating multiple values for an entity called Product in your HTTP POST request. So you created your API method like this in a bout of natural instinct. You were not wrong. ASP.NET is stupid. Because it allows for only one POST body parameter, it forces you to create a separate class to handle multiple parameters.

Do this to fix your woes:

public class Product
{
    int productId { get; set; };
    string productName { get; set; }
}
 
public async Task<HttpResponseMessage> AddProduct(Product prod)
{
    ...
}
Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.