WCF和可选参数

cho*_*obo 17 .net rest wcf optional-parameters

我刚开始使用WCF与REST和UriTemplates.现在可以使用可选参数吗?

如果没有,你们会建议我为一个系统做什么,这个系统有三个常用于url的参数,还有一些是可选的(不同数量)?

例:

https://example.com/?id=ID&type=GameID&language=LanguageCode&mode=free 
Run Code Online (Sandbox Code Playgroud)
  • id,类型,语言总是存在的
  • 模式是可选的

Lad*_*nka 31

我刚用WCF 4进行了测试,它没有任何问题.如果我不在查询字符串中使用模式,我将获取null作为参数的值:

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

方法实施:

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

对我来说,看起来所有查询字符串参数都是可选的.如果查询字符串中不存在参数,则其类型=> nullfor string,0 for for int等的默认值.MS还声明应该实现此参数.

反正你总是可以定义UriTemplateid,typelanguage通过访问内部的方法可选参数WebOperationContext:

var mode = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["mode"];
Run Code Online (Sandbox Code Playgroud)

  • 我想知道如果可选参数是int会发生什么? (2认同)