A FromBody and FromQuery example in ASP.NET Core Web API

Having problems in an ASP.NET Core Web API with using the FromBody or FromQuery attributes?

Maybe you are finding that some of the properties are returning null? Or maybe, you are being greeted with a 415 unsupported media type error.

With this example, we have written an ASP.NET Core Web API in C#, and have provided two controllers, with similar features.

Both controllers both have a HTTP GET request and a HTTP POST request, allowing us to send a JSON request.

However, there is one significant different between the two. One of them contains the ApiController attribute.

The ApiController attribute relies on a JSON request, so we tend to have an issue when we are not sending a JSON request to an API endpoint.

This example demonstrates when we need to use the FromBody attribute, and when we need to use the FromQuery attribute.

Software

This is the software that will need to be installed onto your machine.

  • Visual Studio 2019. Version 16.8.4 or above (may work with lower versions). It will work with the free community version.
  • .NET 5.0 SDK, or above.
  • Postman to test out the endpoints (optional)

Get The Application Working

These are the steps to get the application working.

You are now ready to go.

Open the Project in Visual Studio

Open up RoundTheCode.FromBody.sln in Visual Studio.

You should find that the web application runs on https://localhost:7000.

Start the project in Visual Studio.

You can now run a HTTP GET request (using querystring), and HTTP POST requests (using form-data, x-www-form-url-encoded and application/json content types) using https://localhost:7000/web and https://localhost:7000/webapi.

If you wish to run it in Postman, you can import the scripts from the Postman folder in the source code provided.

More Information

To get a better understanding on how the FromBody and the FromQuery behave, read our article "Why is the ASP.NET Core FromBody not working or returning null?".

In-addition, watch our video tutorial. We demonstrate when our properties are returning null, or when we are getting a 415 error. We then go about fixing them.

Join our Discord Server

  • Can't get your ASP.NET Core application to work? Ask for help here!
  • Discussions with other ASP.NET Core developers.
  • General chat with the community.
Join