2016-07-22 15 views
2

我已經得到了我在我的應用程序想定義了以下路線:ServiceStack可以解析類似的路線嗎?

/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與客戶/或/位置相結合/

回答

3

在ServiceStack中不能有不明確的路由,因此您既可以捕獲所有處理請求的路由,也可以處理到相應服務的路由,例如:

[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在你的服務。

+0

第一種方法的概率是你有一個摘要請求,並且在查看元數據查看Id應該具有的內容時不清楚。 第二種方法的概率是路由簽名的外觀:/ s/locations/{LocationId}/summary,在這種情況下,locationId實際上是位置/ 1234。 任何有關提供基於正則表達式的路由的計劃,或者「攔截」特定傳入請求並動態確定其請求消息的能力? – legion

+0

@legion如果我們允許RegEx路由匹配,我們將無法靜態確定最佳匹配路由,而無需評估每個正則表達式,這會損害性能並中斷反向路由。您可以嘗試使用請求轉換器,它可以讓您返回不同的請求DTO來執行不同的服務。 – mythz