簡體   English   中英

使用查詢字符串參數消除UriTemplate匹配的歧義

[英]Using query string parameters to disambiguate a UriTemplate match

我正在使用WCF 4.0來創建REST-ful Web服務。 我想要做的是根據UriTemplate中的查詢字符串參數調用不同的服務方法。

例如,我有一個API,允許用戶使用其駕駛執照或社會安全號碼作為密鑰來檢索有關某人的信息。 在我的ServiceContract /接口中,我將定義兩個方法:

[OperationContract]
[WebGet(UriTemplate = "people?driversLicense={driversLicense}")]
string GetPersonByLicense(string driversLicense);

[OperationContract]
[WebGet(UriTemplate = "people?ssn={ssn}")]
string GetPersonBySSN(string ssn);

但是,當我使用這兩種方法調用我的服務時,我得到以下異常:

UriTemplateTable不支持具有與模板'people?ssn = {ssn}'等效路徑的多個模板,但具有不同的查詢字符串,其中查詢字符串不能通過文字值消除歧義。 有關更多詳細信息,請參閱UriTemplateTable的文檔。

UriTemplates沒有辦法做到這一點嗎? 這似乎是一種常見的情況。

非常感謝!

或者,如果要保留查詢字符串格式,則可以在UriTemplate的開頭添加靜態查詢字符串參數。 例如:

[OperationContract]
[WebGet(UriTemplate = "people?searchBy=driversLicense&driversLicense={driversLicense}")]
string GetPersonByLicense(string driversLicense);

[OperationContract]
[WebGet(UriTemplate = "people?searchBy=ssn&ssn={ssn}")]
string GetPersonBySSN(string ssn);

我也遇到了這個問題,最終想出了一個不同的解決方案。 我不想為對象的每個屬性使用不同的方法。

我做了如下:

在服務協定中定義URL模板,而不指定任何查詢字符串參數:

[WebGet(UriTemplate = "/People?")]
[OperationContract]
List<Person> GetPersonByParams();

然后在實現中訪問任何有效的查詢字符串參數:

public List<Person> GetPersonByParms()
    {
        PersonParams options= null;

        if (WebOperationContext.Current != null)
        {
            options= new PersonParams();

            options.ssn= WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["ssn"];
            options.driversLicense = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["driversLicense"];
            options.YearOfBirth = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["YearOfBirth"];
        }

        return _repository.GetPersonByProperties(options);
    }

然后,您可以使用URL等搜索

/PersonService.svc/People 
/PersonService.svc/People?ssn=5552
/PersonService.svc/People?ssn=5552&driversLicense=123456

它還使您能夠混合和匹配查詢字符串參數,以便使用您想要的內容並省略您不感興趣的任何其他參數。它的優點是不會將您限制為只有一個查詢參數。

根據這篇文章 ,這是不可能的,你將不得不做這樣的事情:

[OperationContract]
[WebGet(UriTemplate = "people/driversLicense/{driversLicense}")]
string GetPersonByLicense(string driversLicense);

[OperationContract]
[WebGet(UriTemplate = "people/ssn/{ssn}")]
string GetPersonBySSN(string ssn);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM