0
votes

I am sending POST request to my .NET CORE app with Postman and Insomnia, and my breakpoints in the [HttpPost] methods are hit, but the body is empty, and on debugging Visual Studio shows me that the request is a GET Request.

My StartupClass:

namespace MyBuildingRestfulWebWithCore
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddMvc();
            services.AddControllers();
            services.AddSingleton<IProductService, ProductService>();
            services.AddDbContext<FlixOneStoreContext>(options => options.UseSqlServer("myconnectionstring;"));
            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
        }
    }
}

My Controller:

namespace MyBuildingRestfulWebWithCore.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CustomersController : ControllerBase
    {
        private readonly FlixOneStoreContext _context;

        public CustomersController(FlixOneStoreContext context)
        {
            _context = context;
        }


        [HttpGet] //this one works
        public async Task<ActionResult<IEnumerable<Customer>>> GetCustomers()
        {
            return await _context.Customers.ToListAsync();
        }

        [HttpPost("test")] //this one fails because customers variable is null
        public async Task<ActionResult<Customer>> PostCustomers([FromBody] Customer customers)
        {
            if (_context.Customers.Any(customer => customer.Email == customers.Email))
            {
                return StatusCode((int)HttpStatusCode.Conflict, "Email already in use");
            }
            _context.Customers.Add(customers);
            //...
            return CreatedAtAction("GetCustomers", new { id = customers.Id }, customers);
        }
        [HttpPost("test2")] //this one fails because request.Content is null, 
//but Visual Studio debugger shows me that the request.Method is a GET request
        public async Task<ActionResult<string>> PostCustomers(HttpRequestMessage request)
        {
            string body = await request.Content.ReadAsStringAsync();
            return body;
        }
    }

I am using .NET Core 3.0.0, and sent my requests both via Postman and Insomnia to confirm the error is not on the client side - I have set the body in Postman to raw -JSON and in Insomnia to JSON (and my JSON validates)

My request body is as follows:

{
"id":1, 
"gender": "M", 
 "email":"[email protected]",
"firstname": "Firstname",
"lastname": "LastName",
"dob":"1970-07-05T00:00:0",
"mainaddressid":"mainaddr",
"fax":"fax",
"password": "pw",
"newsletteropted": false
}

I have read this article from the offical Docs on how to migrate to .NET Core 3, but didn't find anything helpful.

Any ideas? Am I configuring my startup class wrong, or using some attribute wrong? (I'm not too familiar with .NET Core...)

1
I don't think HttpRequestMessage is supported in aspnet core. Only in classic webapi. You should use this.HttpContext.Request.Body instead - Kalten
You are using SuppressModelStateInvalidFilter with true which suppresses ModelState error; so if your payload object is malformed then post request is invoked with null instead of throwing http bad request (400). Try with false value of SuppressModelStateInvalidFilter. If you gets 400 then correct the payload. Also , can you please post the type definition of Customer class? - user1672994
As says in migration doc, you must use the package Microsoft.AspNetCore.Mvc.WebApiCompatShim to add support to HttpRequestMessage parameters. - Kalten

1 Answers

0
votes

as implied by the commenters to my question, my JSON did not fit my model Class, I just didn't realize this because the fact that HttpRequestMessage is not supported in aspnet core and its method showed as "GET" in the debuggger distracted me from the real issue, and because SuppressModelStateInvalidFilter supressed the error, as noted above.

Removing

services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});

showed me the actual JSON parsing error and helped me correct my input.