【问题标题】:ServiceStack client routes for ExpressJs conditional routesExpressJs 条件路由的 ServiceStack 客户端路由
【发布时间】:2017-09-28 01:08:23
【问题描述】:

ExpressJs 允许您匹配条件(也称为动态或模糊)路由匹配。像GET '/people(/sex/:sexFilter)?(/age-over/:ageOverFilter)?'这样的路由

将匹配以下示例:
/people
/people/sex/female
/people/sex/female/age-over/30
和(最重要的是)/people/age-over/30

我想知道是否有一种方法可以配置 ServiceStack(用于 C# Xamarin 应用程序)客户端,如果请求 dto 对象属性留在null 中,该客户端将生成以下路由,例如:

HttpService.Instance.Get<Person[]>(new SearchPeopleRoute() { sexFilter = "female" });
// Generates /people/sex/female

HttpService.Instance.Get<Person[]>(new SearchPeopleRoute() { ageOverFilter = 30 });
// Generates /people/age-over/30

该解决方案需要可扩展到许多搜索过滤器,因此无法维护每个过滤器排列的 [Route(...)] 属性。

我不知道是否有办法在调用之前在运行时生成路由,但那会很棒。

【问题讨论】:

    标签: c# express routing servicestack


    【解决方案1】:

    在 ServiceStack 中,您需要列出您希望服务能够被调用的不同路由,例如:

    [Route("/people")]
    [Route("/people/sex/{Sex}")]
    [Route("/people/sex/{Sex}/age-over/{AgeOver}")]
    public class SearchPeopleRoute
    {
         public string Sex { get; set; }
         public int? AgeOver { get; set; }
    }
    

    C#/.NET 服务客户端然后根据请求 DTO 填充的内容选择最合适的路由。

    对于 ServiceStack 中的查询,建议您使用 ?queryString 来应用更适合设计 HTTP API 的任何过滤器,因为 /path/info 用于识别资源,而 ?queryString 用于应用修饰符到那个资源请求。

    这个约定是embraced in AutoQuery,它允许您定义一个请求 DTO,例如:

    [Route("/people")]
    public class SearchPeople : QueryDb<Person> {}
    

    并且无需实现该实现即可让您查询 implicit conventions 以获取 Person 表上的任何字段,其中上述 AutoQuery Request DTO 自动支持以下查询:

    /people
    /people?sex=female
    /people?ageOver=30
    /people?sex=female&ageOver=30
    

    【讨论】:

    • 感谢您的出色回答。我想,如果这是 ServiceStack 的唯一解决方案,我将不得不更改我使用的包。太糟糕了,他们不允许您在运行时创建路线。我发现这对他们来说有点死板(也许是故意的)。关于如何形成 REST 路由存在很多争论,当我们做服务器端时,这就是我们选择的方式。将标识符和过滤器在 URL 中表示的方式分开可能是正确的。仔细想想,它们是两个不同的概念。
    猜你喜欢
    • 2014-01-02
    • 2018-02-05
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 2017-11-28
    相关资源
    最近更新 更多