如何在每次web api调用后重置序列化:C#

时间:2017-01-27 14:03:56

标签: c# asp.net json asp.net-web-api

我使用自定义 json序列化来进行特定的API调用。 但它会覆盖全局格式。我需要在此API调用之后或所有其他API调用开始时重置此序列化。

public class ShouldSerializeContractResolver : CamelCasePropertyNamesContractResolver
{
    private List<Serializable> _serializables;

    public ShouldSerializeContractResolver(List<Serializable> serializable)
    {
        _serializables = serializable;
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);

        foreach (var item in _serializables)
        {
            if (item.ObjectType.Contains(property.DeclaringType) && !item.Serialize.Contains(property.PropertyName))
            {
                property.ShouldSerialize =
                   instance =>
                   {
                       return false;
                   };
            }
        }

        return property;
    }
}

我直接从API控制器调用此序列化程序,如下所示:

    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

    List<Serializable> serializableList = new List<Serializable>(); // Model class for storing list of Model classes and corresponding serializable objects as string
        List<Type> listObjectType = new List<Type>();
        List<string> serialize = new List<string>();

        listObjectType.Add(typeof(ModelClassName));
        serialize.Add("classObject1");
        serialize.Add("classObject2");
        serializableList.Add(new Serializable
        {
            Serialize = serialize,
            ObjectType = listObjectType
        });

    json.SerializerSettings.ContractResolver = new ShouldSerializeContractResolver(serializableList); // This is where the serializer is modified

2 个答案:

答案 0 :(得分:1)

我添加了一个“ResetSerializeContractResolverFilter.cs”作为过滤器。

    public class ResetSerializeContractResolverFilter : System.Web.Http.Filters.ActionFilterAttribute
    {
    public ResetSerializeContractResolverFilter()
    {

    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
        json.SerializerSettings.ContractResolver = new DefaultContractResolver();
        base.OnActionExecuting(actionContext);
    }
    }

然后我从“Global.asax”,Application_Start中包含了过滤器,如下所示

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        // Add filter for resetting contractresolver
        var filters = System.Web.Http.GlobalConfiguration.Configuration.Filters;
        filters.Add(new ResetSerializeContractResolverFilter());
    }

因此,将在每个API调用中调用此过滤器,并使序列化程序重置为默认值。

答案 1 :(得分:0)

要在特定操作中使用ShouldSerializeContractResolver序列化程序,您可以将serializerSettings属性与响应一起直接用于mehod。

public HttpResponseMessage Get(){
  List<Product> result = new List<Product>();
      //bind data to list
  var formatter = new JsonMediaTypeFormatter();
  var json =formatter.SerializerSettings;

  json.ContractResolver = new ShouldSerializeContractResolver();

  return Request.CreateResponse(HttpStatusCode.OK, result, formatter);
}