简体   繁体   中英

How can I find the required fields of a JObject in C#, .net?

I have an application and the logs are called through an API. So, I get a 400: Bad Request error when the log Object is empty or http context is null or the model state is not valid. I found out that requestData is labelled as [required] which I assume is the required field. But my lead says he wants all the fields of the log which are required to not throw a 400:Bad request? If anyone can help me, I would be more than happy. Thank you.

I have tried to use swagger and run post a sample json file to see what status code I get, I obviously got a 200 OK , since required Field is in there.

public void Post([FromBody]List<JObject> logData) 
    {
        if (!ModelState.IsValid)
        {
            _logger.LogError(
                $"Bad request - log data not well formed 
{StatusCodes.Status400BadRequest} {logData}");
            throw new BadRequestException("Bad request - log data 
not well formed",
                StatusCodes.Status400BadRequest);
        }
        if (logData?.Count <= 0)
        {
            _logger.LogError(
                $"Bad request - log data not well formed 
{StatusCodes.Status400BadRequest} {logData}");
            throw new BadRequestException("Bad request - log data 
not well formed",
                StatusCodes.Status400BadRequest);
        }
        foreach (var j in logData)
        {
            _logManager.Log(j, HttpContext);

I want to know what are the fields when I pass in the JSON will give 
me a 200 but not 400:Bad Request. Excluding requestData.

JObject is generic and isn't capable of representing 'required'. To be able to do model validation you would have to have a model class that is strongly typed so that you can apply RequiredAttribute to the required properties. Assuming this is a controller action, the framework will automatically map the request to an instance of this if it is able to ( 'model binding' ).

Edit: re-reading the question, I think you may be saying that you don't want to return a 400, but your lead thinks you should. The question isn't very clear. But I think from the code sample you have, your action method has no way of comprehending the notion of required fields and so provided it is sent valid JSON, ModelState.IsValid should always be true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM