ServiceStack 将 C# DTO-Class 导出到 dtos.ts 文件

ServiceStack export C# DTO-Class to dtos.ts file

如何在 npm run typescript-ref http://localhost:5000 src/myproject 生成的 dtos.ts 文件中导出 C# class (DTO) 而无需在请求 class 中引用?

注意: 我们有几个 C# DTO classes(MutationAddressChange、MutationCEOChange...),我们使用自动映射器映射到域 class。所以我们想在 Angular 中也使用 C# DTO classes 来填充相应的类型(例如 MutationAddressChangesCreateDTO)并将其发送到 Web 服务器。因此,在 CreateMutationRequest class 中,我们接受一个对象而不是特定的 class.

示例 DTO-Class:

public class MutationAddressChangesCreateDTO
{
    public string Street { get; set; }
    public string POBox { get; set; }
    public string Zipcode { get; set; }
}

ServiceStack 请求-Class

public class CreateMutationRequest : IPost
{
    public object Mutation { get; set; }
}

Angular 预期用途:

{
    var mutationAddressChangesCreateDTO= new MutationAddressChangesCreateDTO();
    mutationAddressChangesCreateDTO.dateOfMutation = ...

    const request = new CreateMutationRequest ({
        mutation: mutationAddressChangesCreateDTO,
    });

    this.client.post(request)
    ...
}

Add ServiceStack Reference feature is that your DTOs cannot have any object or interface properties 的限制会在您的服务合同中创建一个黑洞,无法为 API 生成 Typed API。

我建议不要 any object or interface properties in your DTOs which other than being a source of runtime issues is also limited by security restrictions

您可以使用像 Dictionary<string,string> 这样的无类型数据结构来存储任意值,您可以在此 Customer Forums thread.

中找到其他替代方案

尽管不鼓励您在 ServiceStack 请求 DTO 中仍然有 object 属性,您只是无法为它们生成类型化的 API 但您仍然可以将它们发送为匿名参数,例如:

this.client.post(request, { mutation: dto });

对象属性使用 JS Utils by default which should deserialize it into a Dictionary<string,object> which you should be able to convert back into a C# type using ServiceStack's Reflection Utils 处理,例如:

public object Any(CreateMutationRequest request)
{
    var payload = request.Mutation as Dictionary<string,object>;
    var payloadRequest = payload.FromObjectDictionary(typeof(TheType));
}

避免使用 object 的类似方法是在 string 属性 中发送序列化的 JSON 有效载荷,例如:

request.mutation = JSON.stringify(payload);

您可以再次使用 JS Utils 反序列化,例如:

public object Any(CreateMutationRequest request)
{
    var payload = JSON.parse(request.Mutation);
    var payloadRequest = payload.FromObjectDictionary(typeof(TheType));
}

话虽如此,我不推荐这些非类型化策略中的任何一种,我会亲自为每个 API 需要的类型化服务创建更加直观、可发现和有弹性的类型化服务,任何共享功能都可以轻松处理使用 ServiceStack 的 AutoMapping 和 .NET 强大的反射功能实现您的服务。