I'm trying out ASP.NET Core MVC and cannot get a route working with a parameter marked with [FromBody]
. I'm using ASP.NET Core 2.2 running on .NET Framework (full, not core). Here's my entire controller:
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace EmailSch.Api.Controllers
{
[ApiController]
[Route("/api")]
public class EmailJobController : ControllerBase
{
public EmailJobController() { }
[Route("emailsch/job"), HttpPost]
public IActionResult RunEmailJob([FromBody]string options)
{
return Ok();
}
}
}
I try calling it from PowerShell using:
Invoke-RestMethod -Uri http://localhost:9000/api/emailsch/job -Method Post -Body 'Hello there'
The result is:
Invoke-RestMethod : The remote server returned an error: (500) Internal Server Error.
No exceptions are thrown in my code and no breakpoints are triggered. If I remove the parameter:
public IActionResult RunEmailJob()
{
return Ok("Hi");
}
It works fine. Is there anything I need to setup in my Startup to get this to work? Here's my entire Startup class:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvcWithDefaultRoute();
}
}
You got 500 Internal Server Error because you didn't specify any InputFormatters
At least one Microsoft.AspNetCore.Mvc.Formatters.IInputFormatter
is required to bind from the body.
To add json formatter use:
services.AddMvcCore().AddJsonFormatters();
or add full MVC with default formatters
service.AddMvc();
then use
Invoke-RestMethod -Uri http://localhost:9000/api/emailsch/job -Method Post -ContentType 'application/json' -Body 'Hello there'
Note: You'll also need to install the Microsoft.AspNetCore.Mvc.Formatters.Json
NuGet package.