Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the request body optional

I've got the following POST function:

public async Task<BaseResponse> Post([FromBody] BodyParams content)
{
    var option = content.TopOnly;
    return await RunHttpMethodAsync(option, _worker.Lookup);
}

Here's the BodyParams class:

public class BodyParams
{
    public bool TopOnly { get; set; }
}

This works as intended. However, I'd like to make BodyParams content as optional, and set TopOnly to true if not provided. I've tried:

public class BodyParams
{
    public bool TopOnly { get; set; } = true;
}

And then not providing a body, but I get the following return:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
    "title": "Unsupported Media Type",
    "status": 415,
    "traceId": "00-305034a9723b9a4f94e0601c6ecc3587-b67fe89deb8e644f-00"
}

I put a breakpoint on my var option, and I don't even reach that.

My question is, how can I make the request body optional for POSTs?

like image 494
PiousVenom Avatar asked Nov 30 '25 14:11

PiousVenom


1 Answers

415 Unsupported Media Type - means that the request entity has a media type which the server or resource does not support.

If you use Postman, set this and try again enter image description here

Also, to make it simpler, you can use

public async Task<BaseResponse> Post([FromBody] TopOnly? topOnly = true)
like image 183
Roman Marusyk Avatar answered Dec 03 '25 04:12

Roman Marusyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!