【问题标题】:Can ServiceStack parse similar routes?ServiceStack 可以解析类似的路由吗?
【发布时间】:2016-07-23 02:12:55
【问题描述】:

我想在我的应用中定义以下路线:

/s/customers/1234/summary

/s/locations/5767/summary

现在通常我会像这样定义我的路线:

Add<CustomerSummaryRequest>("/s/customers/{Id}/summary")
Add<LocationSummaryRequest>("/s/locations/{Id}/summary")

但是问题是,我的数据库中客户和位置的 ID 本身就是

/customers/1234
/locations/5767

并最终希望拥有这些路线:

Add<CustomerSummaryRequest>("/s/{CustomerId*}/summary")
Add<LocationSummaryRequest>("/s/{LocationId*}/summary")

有什么建议吗?

我意识到我可以做到:

Add<CustomerSummaryRequest>("/s/Customers/{CustomerId*}/summary")
Add<LocationSummaryRequest>("/s/Locations/{LocationId*}/summary")

这会给我 id 的数字部分。然后我可以将 id 与 customers/ 或 /locations/ 结合起来

【问题讨论】:

    标签: servicestack


    【解决方案1】:

    你不能在 ServiceStack 中有不明确的路由,所以你可以有一个 catch all Request 来处理请求和路由到适当的服务,例如:

    [Route("/s/{Id*}/summary")]
    public class SummaryRequest 
    {
        public string Id { get; set; }
    }
    
    public object Any(SummaryRequest request)
    {
        var id = "/" + request.Id;
        return request.Id.StartsWith("customers/")
            ? Gateway.Send(new CustomerSummaryRequest { CustomerId = id })
            : Gateway.Send(new LocationSummaryRequest { LocationId = id });
    }
    

    或者您对不同的服务有独特的路线,例如:

    [Route("/s/customers/{CustomerId}/summary")]
    public class CustomerSummaryRequest 
    {
        public int CustomerId { get; set; }
    }
    
    
    [Route("/s/locations/{LocationId}/summary")]
    public class CustomerSummaryRequest 
    {
        public int LocationId { get; set; }
    }
    

    并在您的服务中构建您的 ID。

    【讨论】:

    • 第一种方法的问题是您有一个摘要请求,并且在查看元数据视图时不清楚 Id 应该有什么。第二种方法的问题是路由签名看起来不正确:/s/locations/{LocationId}/summary 在这种情况下,locationId 实际上是位置/1234。是否有计划提供基于正则表达式的路由,或“拦截”特定传入请求并动态确定其请求消息的能力?
    • @legion 如果我们允许正则表达式路由匹配,我们将无法在不评估每个正则表达式的情况下静态确定最佳匹配路由,这会损害性能并破坏反向路由。您可以尝试使用请求转换器,它可以让您返回不同的请求 DTO 来执行不同的服务。
    猜你喜欢
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多