XmlSerializer requires default accessor when returning custom ObjectResult

Viewed 222

I'm receiving an invalid operation exception on my logs even though I'm still receiving a valid response (status 200 OK).

Body Response:

{
    "responseType": "SearchStudents/2019.12.31",
    "body": {
        "students": []
    }
}

How can I get rid of this warning/exception? Here's how I return the Object Result from the controller.

    [HttpPost]
    [Produces("application/json")]
    [Consumes("application/json")]
    [AllowAnonymous]
    [SwaggerRequestExample(typeof(RequestDTO<StudentRequestDTO>), typeof(StudentSearchRequestExampleProvider))]
    [ProducesResponseType(typeof(ResponseDTO<StudentResponseDTO>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ResponseDTO<ErrorResponseDTO>), StatusCodes.Status400BadRequest)]
    [Route("/{apiversion}/student/search")]
public async Task<IActionResult> StudentSearch([FromRoute]string apiversion, dynamic requestDTO, CancellationToken cancellationToken)
{
    var filter = new StudentSearchFilter()
            {
                Version = apiversion,
                RequestDTO = requestDTO
            };
    var response = await searchStudentQuery.Value.ExecuteAsync(filter, User, cancellationToken);
    var result = new ObjectResult(response)
    {
       StatusCode = response.StatusCode,
       Value = response.Body
    };
    return result; 
}

And Here's the exception I'm receiving from logs.

<{ Id: 1, Name: "FailedToCreateXmlSerializer" }> [Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter] [WRN]  An error occurred while trying to create an XmlSerializer for the type '"Newtonsoft.Json.Linq.JObject"'.
System.InvalidOperationException: You must implement a default accessor on Newtonsoft.Json.Linq.JObject because it inherits from ICollection.
   at System.Xml.Serialization.TypeScope.GetDefaultIndexer(Type type, String memberInfo)
   at System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo memberInfo, Boolean directReference)
   at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)
   at System.Xml.Serialization.ModelScope.GetTypeModel(Type type, Boolean directReference)
   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type)
   at Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter.CreateSerializer(Type type)

the error appears during return result

==================================== EDIT

I'm returning a deserialize object from the searchStudentQuery hope it helps

return new ClientResponseProxy()
{
       StatusCode = (int)result.StatusCode,
       Body = JsonConvert.DeserializeObject<dynamic>(await result.Content.ReadAsStringAsync())
};

=============================== EDIT 2 Here's the Configure Services

   services.AddMvc(o =>
   {
        o.RespectBrowserAcceptHeader = true;
        o.Conventions.Add(new AdminGuiAuthorizeConvention("Web"));
        o.Conventions.Add(new MobileUserAuthorizeConvention("Mobile"));
        o.Filters.Add(new KeyNotFoundExceptionFilter());
        o.Filters.Add(new KeyNotFoundMobileExceptionFilter());
        o.Filters.Add(new UnauthorizedAccessExceptionFilter());
        o.Filters.Add(new DevelopersApiFilter(Configuration["DevelopersAPIEnabled"] == bool.TrueString));
        o.OutputFormatters.Add(new HtmlOutputFormatter());
   }).AddXmlSerializerFormatters()
     .AddApplicationPart(typeof(Rest.Controllers.V1.CustomerController).Assembly)
     .AddNewtonsoftJson(options => options.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error)
     .AddNewtonsoftJson(options => options.SerializerSettings.Converters.Add(new StringEnumConverter()));
0 Answers
Related