There's a ton of stuff around best practice for this - some say each controller should only have one POST; others disagree.
I finally decided to break the controllers up by category and then within each controller have multiple POST functions.
I also added Swagger via Swashbuckle and used Postman for some unit tests so I thought I would write this all up.
As an example, I have a Maths controller with Add and Multiply.
The controller:
using MathsWebAPI.Models;
using System.Web.Http;
namespace MathsWebAPI.Controllers
{
public class MathsController : ApiController
{
// POST: api/Maths
[HttpPost]
public int Add([FromBody] Maths info)
{
int number1 = info.number1;
int number2 = info.number2;
return (number1 + number2);
}
// POST: api/Maths
[HttpPost]
public int Multiply([FromBody] Maths info)
{
int number1 = info.number1;
int number2 = info.number2;
return (number1 * number2);
}
}
}
Note that I am passing in a model object as I have multiple parameters.
The model object:
namespace MathsWebAPI.Models
{
public class Maths
{
public int number1 { get; set; }
public int number2 { get; set; }
}
}
The WebAPIConfig.cs:
using System.Web.Http;
namespace MathsWebAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
/*config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);*/
config.Routes.MapHttpRoute(
name: "ControllerAndAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new {id = RouteParameter.Optional}
);
}
}
}
In SwaggerConfig.cs, uncomment:
c.DisableValidator();
to avoid the error message.
Now if I navigate to:
http://localhost:44571/swagger
where 44571 is my IIS Express port
I see:
Now if you click the yellow area, it will populate the "Info" box with the model object format and you just have to fill in the values.
Click "Try it out" and you see:
Note the URL is:
api/Maths/Add
Now if we add Postman, the commands are in this gist.
Running the script, we see:
Enjoy!