我在尝试使用WCF使用简单服务时遇到问题.到目前为止,除了实现可选的查询字符串参数之外,一切都进展顺利.界面看起来有点像这样:
[ServiceContract]
[XmlSerializerFormat]
public interface IApi
{
[OperationContract]
[WebGet(UriTemplate = "/url/{param}?top={top}&first={first}")]
object GetStuff(string param, int top, DateTime first);
}
Run Code Online (Sandbox Code Playgroud)
然后通过创建一个继承的类来消耗它ClientBase<IApi>.我尝试了几种方法使参数可选:
1)使参数可以为空
这没用.我从QueryStringConverter另一个问题得到一条消息:WCF服务合同可以有一个可以为空的输入参数吗?
2)URL末尾的一个参数
因此,我考虑将UriTemplate更改为更通用,构建查询字符串并将其作为参数传递.这似乎也不起作用,因为传入的值被编码,使得它不被服务器识别为查询字符串.
例:
[WebGet(UriTemplate = "/url/{query}")]
Run Code Online (Sandbox Code Playgroud)
3)Hackish Solution
到目前为止我找到的唯一方法是将所有参数更改为字符串,并且这里似乎允许使用NULL.
例:
[WebGet(UriTemplate = "/url/{param}?top={top}&first={first}")]
object GetStuff(string param, string top, string first);
Run Code Online (Sandbox Code Playgroud)
此接口的使用仍然接受正确的变量类型,但是ToString被使用.Thes查询字符串参数仍出现在实际请求中.
那么,使用WCF 消费 REST服务有没有办法让查询字符串参数可选?
更新 - 如何修复
提出了创建服务行为的建议.这继承自WebHttpBehaviour.它看起来如下:
public class Api : ClientBase<IApi>
{
public Api() : base("Binding")
{
Endpoint.Behaviors.Add(new NullableWebHttpBehavior());
}
}
Run Code Online (Sandbox Code Playgroud)
该NullableWebHttpBehavior可在下列问题#1中找到:一个WCF服务合同可以有一个为空的输入参数?.唯一的问题是,ConvertValueToString没有超载,所以我快速打了一个:
public override string ConvertValueToString(object parameter, Type parameterType)
{
var underlyingType = Nullable.GetUnderlyingType(parameterType);
// Handle nullable types
if (underlyingType != null)
{
var asString = parameter.ToString();
if (string.IsNullOrEmpty(asString))
{
return null;
}
return base.ConvertValueToString(parameter, underlyingType);
}
return base.ConvertValueToString(parameter, parameterType);
}
Run Code Online (Sandbox Code Playgroud)
这可能不完美,但似乎按预期工作.
您的选项 1) 可以适用于 WCF 客户端,因为它WebHttpBehavior可以应用于 ClientBase(或 ChannelFactory)派生类,如此SO 问题和答案中所示。只需将您在 1) 中引用的代码与捕获 500 个响应问题中显示的配置结合起来,它就会显示出工作效果。