2

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()));
Yzak
  • 81
  • 2
  • 13
  • 3
    Your `ObjectResult` contains a [`JObject`](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm) which is a Newtonsoft.Json class that represents an arbitrary JSON object. And, for some reason, you are trying to serialize it to XML with `XmlSerializer`. But, you can't do that because `XmlSerializer` does not know how to transcode JSON to XML. That being said, your API is marked with `Produces("application/json")]` so why is it trying to return XML? Do you really want to be able to return XML or is that the real bug? – dbc Feb 22 '22 at 14:32
  • the searchStudentQuery is returning a response from a deserialized object I added the code above – Yzak Feb 23 '22 at 08:21
  • Your question is still a little unclear. Are you trying to return XML, or JSON? Does the `StudentSearch()` API call return correct results (as opposed to just status 200 OK) despite the error message in the logs, or return incorrect results with the error message shown in the logs? If the returned body is correct, is the only problem the unwanted error message, or is there some other problem? – dbc Feb 24 '22 at 15:54
  • Also, what ASP.NET framework and version are you using? – dbc Feb 24 '22 at 15:57
  • Do you *ever* want to return XML, or do you only ever want to return JSON even if the request has `Accept: application/xml`? – dbc Feb 24 '22 at 16:03
  • I'm trying to return a JSON, yes the api call return correct response the only time I see the exception is when I look at the logs with or without student data.. I want to get rid of this exception because whenever I check the logs for errors it was flooded with it – Yzak Feb 25 '22 at 03:01
  • using .NET Core – Yzak Feb 25 '22 at 04:15
  • Which version of ASP.NET Core? What does your `ConfigureServices()` look like? Any chance you are adding `XmlSerializerOutputFormatter` to `options.OutputFormatters` there? – dbc Feb 25 '22 at 15:06
  • I added the configure service where xml serializer is configured and the api is part of a controller with group name [ApiExplorerSettings(GroupName = "Mobile")] – Yzak Feb 28 '22 at 05:24
  • Why are you doing `AddXmlSerializerFormatters()` if you don't want XML output? Can you just remove it? Because it's the XmlSerializerOutputFormatter which is throwing the exception, trying to serialize a JSON object. – dbc Feb 28 '22 at 05:49
  • Some Controllers might be using it, can we make an exception to specific controller?? – Yzak Feb 28 '22 at 10:12
  • Well see [Configure input/output formatters on controllers with ASP.NET Core 2.1](https://stackoverflow.com/q/51769415/3744182). You'll want to remove `XmlSerializerOutputFormatter` for your controller or method. – dbc Feb 28 '22 at 14:52
  • 1
    Seems like the exception is getting logged from [`XmlSerializerOutputFormatter.CanWriteType(Type type)`](https://github.com/aspnet/Mvc/blob/master/src/Microsoft.AspNetCore.Mvc.Formatters.Xml/XmlSerializerOutputFormatter.cs#L144) which calls `CreateSerializer(Type type)` which just returns false in case the serializer can't be created -- but also logs the exception, which you don't want. – dbc Feb 28 '22 at 14:56
  • I tried to supress the warning from Program.cs but the error still appear logging.AddSerilog(); logging.AddFilter("Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter", LogLevel.Warning); – Yzak Mar 29 '22 at 04:11

0 Answers0