[OperationContract]
[WebGet(UriTemplate = "/searchresults/{searchTerm}/{searchType}", ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
Message GetSearchResults(string searchTerm, string searchType);
[OperationContract]
[WebGet(UriTemplate = "/searchresults/{searchTerm}", ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
Message GetSearchResults(string searchTerm);
这是否可能 - 如果没有,有人可以提出替代方案吗?
我发现这对我来说是最好的解决方案:
[OperationContract(Name = "SearchresultsWithSearchType")]
[WebGet(UriTemplate = "/searchresults/{searchTerm}/{searchType=null}",
ResponseFormat = WebMessageFormat.Xml)]
Message GetSearchResults(string searchTerm, string searchType);
[OperationContract(Name = "SearchresultsWithoutSearchType")]
[WebGet(UriTemplate = "/searchresults/{searchTerm}",
ResponseFormat = WebMessageFormat.Xml)]
Message GetSearchResults(string searchTerm);
匹配:
"http://myservice/searchresults/mysearchterm"
"http://myservice/searchresults/mysearchterm/"
"http://myservice/searchresults/mysearchterm/mysearchtype"
不,不是真的 - 因为字符串参数searchType
可以为NULL - 所以你真的没有办法区分这两个URL模板。如果您使用非可空类型(如INT
或其他东西)会有所不同 - 那么您(和.NET运行时)可以将两个URL模板分开(基于INT是否存在的事实)。
你需要做的只是检查你的searchType
方法中GetSearchResults
是空还是NULL,并采取相应的行动。
[OperationContract]
[WebGet(UriTemplate = "/searchresults/{searchTerm}/{searchType}", ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
Message GetSearchResults(string searchTerm, string searchType);
并在您的实施中:
public Message GetSearchResults(string searchTerm, string searchType)
{
if(!string.IsNullOrEmpty(searchType))
{
// search with searchType
}
else
{
// search without searchType
}
......
}
我通过使用STREAM从客户端传递数据来实现这一目标。您甚至可以使用相同名称但方法名称不同的2个操作。从前端确保将contentType设置为“text / javascript”或“application / octet-stream”,并尝试将数据作为POST从HTML或数据变量发送,如果使用AJAX或jQuery
例如
[OperationContract]
[WebInvoke(Method = "PUT", UriTemplate = "user/id/{id}/", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
string UpdateUser(string id, System.IO.Stream stream);
[OperationContract]
[WebInvoke(Method = "DELETE", UriTemplate = "user/id/{id}/", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
string DeleteUser(string id);
或者用PUT和DELETE代替GET和POST