我正在开发示例应用程序,以使用REST API从服务器获取就业数据。
[OperationContract]
[WebGet(UriTemplate = "/employ?id={empIDs}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
List GetEmpList(string empIDs);
为了获得雇员的详细信息,我打电话给它并且工作正常。
GetEmpList("1");
上面的代码只需要一个ID,但我想要多个雇佣细节。然后为了获得多个工作,我需要使用URL <root>/employ?1d=1&id=41&id=45
但为了解决这个问题,我调用了GetEmpList()
API,如下所示
GetEmpList("1&id=41&id=45");
但它给了我一个例外:
System.ServiceModel.EndpointNotFoundException
消息:
在https://sample.com/rest/employ?id=221%26id%3d211%26id%3d%26id%3d1057%26id%3d%26id%3d445没有可以接受该消息的端点监听。这通常是由错误的地址或SOAP操作引起的。有关更多详细信息,请参阅InnerException(如果存在)。
如果我将URL硬编码为
[OperationContract]
[WebGet(UriTemplate = "/employ?id={empIDs}&id={empIDs2}&id={empIDs3}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
List GetEmpList(string empIDs, string empIDs2, string empIDs3);
然后它可以工作,但问题是雇佣人数因请求而异。
我的问题是如何将多个参数传递给UriTemplate
?
答案 0 :(得分:0)
在查询字符串中传递数组类型参数没有标准方法,但您可以相当容易地自己完成。假设您的所有员工ID都是整数,可能最简单的方法(从技术和人类可读的角度来看)将它们作为逗号分隔的字符串传递。
示例(与原始代码相同):
[OperationContract]
[WebGet(UriTemplate = "/employ?id={empIDs}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
List GetEmpList(string empIDs);
呼叫:
GetEmpList("1,2,13");
在方法实现中,您只需执行以下操作:
var ids = empIDs.Split(new [] { ',' }).Select(id => Int32.Parse(id));
另见this answer。