WCF and optional parameters

前端 未结 3 881
无人及你
无人及你 2020-12-15 20:27

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

3条回答
  •  清酒与你
    2020-12-15 20:58

    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.

提交回复
热议问题