Asp.net FromBody fails when payload is null

143 views Asked by At

I have a controller that expects to get a json payload ie

public async Task<IActionResult> InitUser([FromBody] Tenant tenant)

This is fine when a valid json payload is sent, but if no payload is sent I get the error

No input formatter was found to support the content type 'null' for use with the [FromBody] attribute

And HTTP status code 415 is returned to the client.

Is it possible to catch this case and set the json payload to some default value so that the input formatter wont throw this error?

1

There are 1 answers

0
Daniel Paiva On

You can remove the [FromBody] attribute and get the body directly from the HTTP request. Make sure you have the [HttpPost] Attribute decoration.

In the example below you can see how to do that in a very simple way. You can also create your own CustomAttribute and middleware if you want to make it a system wide and elegant solution.

You will also need to parse the body. For that you can use JsonConverter if you like.

[HttpPost]
        public async Task<IActionResult> Index()
        {
            Tenant tenant;
            string result;
            using (var reader = new StreamReader(Request.Body))
            {
                var body = await reader.ReadToEndAsync();

                result = body;
            }

            //Define the naming strategy here if you need
            DefaultContractResolver contractResolver = new DefaultContractResolver
            {
                //NamingStrategy = new SnakeCaseNamingStrategy()
                NamingStrategy = new CamelCaseNamingStrategy()
            };

            //Optional configuration to add in DeserializeObject constructor as second param.
            var jsonSerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = contractResolver,
            };

            tenant = JsonConvert.DeserializeObject<Tenant>(result);

            Console.WriteLine(tenant);
            return View();
        }