我正在使用 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
?这似乎是一个常见的场景。
非常感谢!
我也遇到了这个问题,最终想出了一个不同的解决方案。我不想为对象的每个属性使用不同的方法。
我所做的如下:
在服务合同中定义 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
它还使您能够混合和匹配查询字符串参数,因此只需使用您想要的参数并省略您不感兴趣的任何其他参数。它的优点是不限制您只能使用一个查询参数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)