【问题标题】:WCF and optional parametersWCF 和可选参数
【发布时间】:2011-04-25 17:54:35
【问题描述】:

我刚开始使用带有 REST 和 UriTemplates 的 WCF。现在可以使用可选参数吗?

如果不是,你们会建议我为一个具有三个始终在 url 中使用的参数以及其他可选参数(可变数量)的系统做什么?

例子:

https://example.com/?id=ID&type=GameID&language=LanguageCode&mode=free 
  • id、类型、语言始终存在
  • 模式是可选的

【问题讨论】:

  • 没有什么特别的事情要做。只需检查 mode 参数的 string.IsNullOrEmpty,如果它为 null 或空,则分配一个默认值。
  • 我有同样的问题,在 .NET 4 中......必须在某处设置一些东西......任何提示?

标签: .net wcf rest optional-parameters


【解决方案1】:

我刚刚使用 WCF 4 对其进行了测试,并且没有任何问题。如果我不在查询字符串中使用模式,我将得到 null 作为参数的值:

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebGet(UriTemplate = "GetData?data={value}&mode={mode}")]
    string GetData(string value, string mode);
}

方法实现:

public class Service : IService
{
    public string GetData(string value, string mode)
    {
        return "Hello World " + value + " " + mode ?? "";
    }
}

在我看来,所有查询字符串参数都是可选的。如果查询字符串中不存在参数,则其类型将具有默认值 => null 表示 string,0 表示 int 等。MS also states 应该实现这一点。

无论如何,您始终可以使用idtypelanguage 定义UriTemplate,并通过WebOperationContext 访问方法内部的可选参数:

var mode = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["mode"];

【讨论】:

  • @John:好问题。我尝试了int 并编辑了我的答案。
  • 谢谢。很困惑,因为我读到了很多关于此的相互矛盾的信息。
  • 我之前试过了,效果不错,现在可以了。看下面的问题stackoverflow.com/questions/2969238/…
【解决方案2】:

我尝试过在 RESTful Web 服务中使用可选参数, 如果我们没有在参数值中传递任何东西,它仍然为空。之后我们可以检查 函数中的 null 或空。如果它为空,则不要使用它,否则你可以使用它。 假设我有以下代码

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebGet(UriTemplate = "GetSample?part1={part1}&part2={part2}")]
    string GetSample(string part1, string part2);
}

这里第 1 部分是强制性的,第 2 部分是可选的。 现在函数看起来像

public class Service : IService
{
    public string GetSample(string part1, string part2)
    {
        if (!string.IsNullOrEmpty(part2))
        {
            return "Hello friends..." + part1 + "-" + part2;
        }
        return "Hello friends..." + part1;
    }
}

您也可以根据自己的要求进行转换。

【讨论】:

    【解决方案3】:

    你必须使用“?”在您的网址中后跟“/”。

    示例:

    [WebGet(UriTemplate = "GetSample/?OptionalParamter={value}")]
        string GetSample(string part1);
    

    【讨论】:

    • 这是指定查询字符串的常规方式,与可选参数无关。
    猜你喜欢
    • 2011-02-08
    • 2013-06-19
    • 2023-03-04
    • 1970-01-01
    • 2016-03-30
    • 2023-04-03
    • 2013-02-14
    • 2019-12-15
    • 1970-01-01
    相关资源
    最近更新 更多