【问题标题】:Consuming REST Service with WCF - Optional Querystring Parameters?使用 WCF 使用 REST 服务 - 可选的查询字符串参数?
【发布时间】:2012-05-10 18:35:43
【问题描述】:

我在尝试使用 WCF 使用简单服务时遇到问题。到目前为止,一切都很顺利,除了实现可选的查询字符串参数。界面看起来有点像这样:

[ServiceContract]
[XmlSerializerFormat]
public interface IApi
{
    [OperationContract]
    [WebGet(UriTemplate = "/url/{param}?top={top}&first={first}")]
    object GetStuff(string param, int top, DateTime first);
}

然后通过创建一个继承ClientBase<IApi> 的类来消耗它。我尝试了几种使参数可选的方法:

1) 使参数可以为空

这不起作用。我收到了来自QueryStringConverter 的消息,就像另一个问题一样:Can a WCF service contract have a nullable input parameter?

2) URL 末尾的一个参数

因此,我考虑将 UriTemplate 更改为更通用,构建查询字符串并将其作为参数传递。这似乎也不起作用,因为传入的值被编码,因此服务器不会将其识别为查询字符串。

例子:

[WebGet(UriTemplate = "/url/{query}")]

3) 黑客解决方案

到目前为止,我发现让它工作的唯一方法是将所有参数更改为字符串,这里似乎允许使用 NULL。

例子:

[WebGet(UriTemplate = "/url/{param}?top={top}&first={first}")]
object GetStuff(string param, string top, string first);

这个接口的消费仍然接受正确的变量类型,但是使用了ToString。这些查询字符串参数仍然出现在实际请求中。

那么,有没有办法在使用使用 WCF 的 REST 服务时,使查询字符串参数成为可选参数?

更新 - 如何修复

已采纳创建服务行为的建议。这继承自WebHttpBehaviour。它看起来如下:

public class Api : ClientBase<IApi>
{
    public Api() : base("Binding")
    {
        Endpoint.Behaviors.Add(new NullableWebHttpBehavior());
    }
}

NullableWebHttpBehavior 可以在以下 Stackoverflow 问题中找到:Can a WCF service contract have a nullable input parameter?。唯一的问题是,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);
    }

这可能并不完美,但它似乎按预期工作。

【问题讨论】:

  • 这显示了 wcf 的糟糕程度。难以置信你要跳多少圈才能完成这么简单的事情
  • @jere 同意,这令人失望。
  • 同意 wcf 对于创建 REST 风格的应用程序来说过于复杂。 wcf 试图解决的问题是使服务可在不同的协议(tcp、msmq 和 http)上公开,而 rest 本质上与 http 相关联。所以你可以争辩说 wcf 是实现休息服务的错误选择。

标签: c# .net wcf


【解决方案1】:

您的选项 1) 可以用于 WCF 客户端,因为 WebHttpBehavior 可以应用于 ClientBase(或 ChannelFactory)派生类,如 SO question & answer. 所示,只需将您在 1) 中引用的代码与显示的配置结合起来在捕获 500 个响应的问题中,它显示了工作。

【讨论】:

  • 谢谢。我已将实施细节添加到我的答案中。
【解决方案2】:

您是否尝试过使用可为空的类型?

object GetStuff(string param, int? top, DateTime? first);

【讨论】:

    猜你喜欢
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 2011-10-13
    • 2011-07-22
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多