C#C
C#3y ago
Ysehporp

❔ WEBAPI [FromBody] Json with optional elements

I am building a .net Wep API application where I will be receiving requests where all of the data is in the JSON body. I understand this is not the preferred way to do this but this is how I have to do it for this application. I will receive a post from my frontend which essentially looks like this
{
        "userID": "",
        "token": "",
        "conversationID": "",
        "starttimestamp": "", optional
        "endtimestamp": "", optional
}

My code is able to process this provided both startTimestamp and endTimestamp are occupied. However as they are optional attributes they will sometimes be absent from requests and in those cases I receive an error
{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-8e1d4ff06e05e21050e95e3255d1828b-57d0cca122b223fd-00",
    "errors": {
        "endtimestamp": [
            "The endtimestamp field is required."
        ],
        "starttimestamp": [
            "The starttimestamp field is required."
        ]
    }
}

I would like to be able to make these field not required but I am uncertain how.
My method which receives the request starts like this
 [HttpPost]
        [Route("RouteHere")]
        public string reqUpdate([FromBody] MessageUpdate req)
        {
Was this page helpful?