从Autorest生成的代码中深度克隆对象

时间:2019-01-30 23:45:26

标签: c# serialization swagger autorest

我正在使用Autorest生成代码来调用我的api。

我想在单元测试中使用以下内容

    private JobHeaderRequestObject MakeRequestFromResponse(JobHeaderResponseObject InResponseObject)
{
    // make use of the fact that in the server side code we know  JobHeaderResponseObject inherits from JobHeaderRequestObject 
    return MySerializer.DeepConvert<JobHeaderResponseObject,JobHeaderRequestObject>(InResponseObject);
}


internal class MySerializer
{

    public static T2 DeepConvert<T1,T2>(T1 obj)
    {
        using (var ms = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            ms.Position = 0;
            return (T2)formatter.Deserialize(ms);
        }
    }
}

但是,当我尝试运行此代码时,出现错误提示

System.Runtime.Serialization.SerializationException   

指示类型

is not marked as serializable

我不想遍历生成的添加属性的代码

[可序列化]

每种类型,因为下次我生成代码时,代码将被覆盖。

我看着this issue on the Git Hub project,其中提到

  

如果swagger规范具有这样的模型定义

{
  "Foo": {
    "properties": {
      "name": {
        "type": "string"
      },
      "age": {
        "type": "number"
      }
    },
    "additionalProperties": {
      "type": "string"
    }
  }
}
  

然后,Autorest生成的SDK应该能够序列化并   正确反序列化(往返)未知属性。

     

今天,生成的C#客户端通过使用Dictionary AdditionalProperties支持此功能。

所以现在我试图了解什么是Autorest规范以及如何设置它。

在startup.cs中,我在“配置”中

            app.UseSwagger(c =>
        {
            c.RouteTemplate =
                "api-docs/{documentName}/swagger.json";
        });



        app.UseSwaggerUI(c =>
        {
            //Include virtual directory if site is configured so
            c.RoutePrefix = "api-docs";
            c.SwaggerEndpoint("./v1/swagger.json", "Api v1");

        });

在我拥有的ConfigureServices中

        services.AddSwaggerGen(c =>
        {
            c.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
            c.SwaggerDoc("v1", new Info
            {
                Version = "v1",
                Title = "My API",
                Description = "ASP.NET Core Web API",
                TermsOfService = "None",
                Contact = new Swashbuckle.AspNetCore.Swagger.Contact
                {
                    Name = "MyName",
                    Email = "MyEmail@Mydomain.com"
                }


            });

            c.EnableAnnotations();
            c.DescribeAllEnumsAsStrings();
            c.ParameterFilter<SwaggerEnumParameterFilter>();
            c.SchemaFilter<SwaggerEnumFilter>();
        });

0 个答案:

没有答案