WCF and optional parameters

老子叫甜甜 提交于 2019-12-29 05:06:31

问题


I just started using WCF with REST and UriTemplates. Is it now possible to use optional parameters?

If not, what would you guys recommend I do for a system that has three parameters that are always used in the url, and others that are optional (varying amount)?

Example:

https://example.com/?id=ID&type=GameID&language=LanguageCode&mode=free 
  • id, type, language are always present
  • mode is optional

回答1:


I just tested it with WCF 4 and it worked without any problems. If I don't use mode in query string I will get null as parameter's value:

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

Method implementation:

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

For me it looks like all query string parameters are optional. If a parameter is not present in query string it will have default value for its type => null for string, 0 for int, etc. MS also states that this should be implemented.

Anyway you can always define UriTemplate with id, type and language and access optional parameters inside method by WebOperationContext:

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



回答2:


I have tried with optional parameters in restful web service, If we do not pass anything in parameter value it remains null. After that we can check for the null or empty in function. If it is null then don't use it, else you can use it. Let say I have below code

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

Here part1 is compulsory and part2 is optional. Now the function would look like

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

You can also make the conversion based on your requirements.




回答3:


You have to use "?" followed by "/" in your Url.

example:

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


来源:https://stackoverflow.com/questions/5781342/wcf-and-optional-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!