【问题标题】:ServiceStack: how to change member attributes in the API model at service startup?ServiceStack:如何在服务启动时更改 API 模型中的成员属性?
【发布时间】:2016-08-04 16:17:50
【问题描述】:

我们将 ServiceStack 用于我们用 C# 开发的 Web API。我想在 Web 服务启动时更改我们数据成员的必需属性。

目前所需的属性是在编译时以这种方式定义的:

[ApiMember(IsRequired=true)]
public string MyAttribute { get; set; }

我想在执行 AppHost.Configure 时“动态”定义它的值。

有没有办法通过 ServiceStack 实现这一点?以同样的方式,我们使用 Fluent api 定义路由(例如:Routes.Add<HOPFlight>("/flight", "POST");)?

我阅读了答案Dynamically adding attributes in ServiceStack,它建议在 AppHost 构造函数中执行此操作,但该怎么做?

【问题讨论】:

    标签: c# rest asp.net-web-api servicestack


    【解决方案1】:

    您链接的问题在原始问题中提供了一个示例。请注意,如果您尝试将其添加到 AppHost 的配置功能中,则可能为时已晚。您应该将它添加到 AppHost 的构造函数中。从您的链接问题中,mythz 说

    要动态添加服务属性,您需要先添加它们 AppHost.Configure() 因为它们已经被初始化了 Configure() 已运行,因此需要在 AppHost 中添加它们 构造函数或在调用 AppHost.Init() 之前。

    在你的情况下,这样的事情应该可以工作,

    public AppHost(string serviceName, Assembly[] serviceAssemblies) : base(serviceName, serviceAssemblies)
    {
        ApiMemberAttribute requiredAttribute = new ApiMemberAttribute {
            IsRequired = true
        } 
    
        Type[] requiredApiMembers = GetTypesToAddApiMemberAttributeTo();  //do whatever you need to get the types you want to add attributes to
        foreach(requiredApiMember in requiredApiMembers)
        {
          requiredApiMember.AddAttributes(requiredAttribute);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-28
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多