Home > Back-end >  PostAsJsonAsync not calling the Controller when <Tvalue> has null fields
PostAsJsonAsync not calling the Controller when <Tvalue> has null fields

Time:06-12

My TValue object has foreign key related objects, which has null values when posting; I am having the logic to set the FK objects in the repository. The issue I am facing is that API controller is not getting called when FK objects have all fields null. Please see screenshot. The same code works if I set the value for all but the ID field of the FK objects from the front end.

Is the issue because Json serializer checking for nulls? I have also tried to set the null check ignore option. I am not getting an error on PostAsJsonAsync and the control simply goes to the next line of code

return await result.Content.ReadFromJsonAsync();

without calling the API controller and send an exception

public async Task<SubContract> AddSubContract(SubContract subContract)
    {
        /* On the injected httpClient, call the PostAsJsonAsync method and pass the subContractObject
         * We also need to specifi the api Uri in  the parameter list */

        JsonSerializerOptions option = new()
        {
            DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
        };

        var result = await httpClient
            .PostAsJsonAsync<SubContract>("api/SubContracts", subContract, option);

        //Use the content object and ReadFromJsonSync method and typecast it to <SubContract>             
        
        return await result.Content.ReadFromJsonAsync<SubContract>();
    }

Screenshot

CodePudding user response:

you must be using Net 6 API, and it causes a validation error. Try to comment Nullable in your API project (your serializer option is not working in this case)

<PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <!--<Nullable>enable</Nullable>-->
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

CodePudding user response:

@Serge Thanks for the response. You are right, I am using .Net 6. I have now commented out the nullable but I still have the same issue. Further, I tried to change the function to PostAsync instead of PostAsJsonAsync; below is the new code

// ---- Post Asysc Option -----
            var subContractSeralized = JsonSerializer.Serialize(subContract, option);

            var stringContent = new StringContent(subContractSeralized,
                encoding: System.Text.Encoding.UTF8, "application/json");

            var response = await httpClient.PostAsync("api/subcontract", stringContent);

            return await response.Content.ReadFromJsonAsync<SubContract>();

I initially thought it was a serialization issue because of the nulls in the nested object but when I debug the new code, I get the below result

subContractSerealized = '{"Id":0,"Name":"Aquatic-Repairs","Status":"In-Progress","WorkTypeId":1002,"WorkType":{"Id":0},"SiteId":3,"Site":{"Id":0},"OrganizationId":3,"Organization":{"Id":0}}'

If you compare this with the Debug screen shot in my first post, you can see that the null value fields in the nested objects are omitted out

Response StatusCode = “Not Found-404”

I am not sure how Response Status code is obtained as the API is not called. I.e. httpClient.PostAsync does not transfer control to the API and my debug breakpoint is not hit.

I tried the same code for an Entity model that has no nested foreign key related objects and it works fine and I am able to add the record to the DB. I have the “Required” validation set on the field properties of the entity models; however, after the API call, I have my repository that is taking care of it. So, I doubt that is an issue. In any case, the code is not even hitting the API and simply returns an 404 NotFound on httpClient.PostAsync.

  • Related