How to set IgnoreSerializableAttribute = true for JsonMediaTypeFormatter used by ReadAsAsync() within Microsoft.AspNet.WebApi.Client nuget package

  Kiến thức lập trình

originally posted on microsoft’s github but asked to post on stack overflow instead.

Microsoft.AspNet.WebApi.Client exposes an extension method HttpContentExtensions.ReadAsAsync which depends on MediaTypeFormatterCollection which creates a default set of MediaTypeFormatter one of which is JsonMediaTypeFormatter which depends on Newtonsoft.Json. This media type formatter has a setting IgnoreSerializableAttribute = true buried within SerializerSettings.ContractResolver that we want to set. It appears the only way to do this is by using an override of ReadAsAsync that takes an enumerable of custom media type formatters.

Is there a global way to set IgnoreSerializableAttribute = true for all media type formatters at a global level? This is behavior we never want.

With the current approach we have to visit ~75 instances of ReadAsAsync and switch them to a custom extension method that uses a JsonMediaTypeFormatter with IgnoreSerializableAttribute = true which is pretty tedious and testing intensive. Furthermore, we have to enforce the usage of the custom extension and “ban” the native ReadAsAsync with Roslyn Analyzers.

public static Task<T> ReadAsAsyncAndIgnoreSerializableAttrib<T>(this HttpContent content)
  var mediaTypeFormatter = new List<MediaTypeFormatter>() { new System.Net.Http.Formatting.JsonMediaTypeFormatter()
  
  {
      SerializerSettings = new JsonSerializerSettings()
      {
          ContractResolver = new DefaultContractResolver()
          {
              IgnoreSerializableAttribute = true
          }
      }
  } };
  
  return content.ReadAsAsync<T>(mediaTypeFormatter);
}

New contributor

Brian P Williams is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT