Using query string parameters to disambiguate a UriTemplate match

前端 未结 3 1639
萌比男神i
萌比男神i 2021-02-07 01:40

I am using WCF 4.0 to create a REST-ful web service. What I would like to do is have different service methods called based on query string parameters in the UriTemplate<

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-07 02:19

    I also ran into this problem and eventually came up with a different solution. I didn't want to have a different method for each property of an object.

    What I did was as follows:

    Define the URL Template in the service contract not specifying any query string parameters:

    [WebGet(UriTemplate = "/People?")]
    [OperationContract]
    List GetPersonByParams();
    

    Then in the implementation access any valid query string parameters:

    public List GetPersonByParms()
        {
            PersonParams options= null;
    
            if (WebOperationContext.Current != null)
            {
                options= new PersonParams();
    
                options.ssn= WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["ssn"];
                options.driversLicense = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["driversLicense"];
                options.YearOfBirth = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["YearOfBirth"];
            }
    
            return _repository.GetPersonByProperties(options);
        }
    

    You can then search by using URL's such as

    /PersonService.svc/People 
    
    /PersonService.svc/People?ssn=5552
    
    /PersonService.svc/People?ssn=5552&driversLicense=123456
    

    It also enables you to mix and match query string parameters so just use what you want and omit any other params you're not interested in. It has the advantage of not restricting you to just one query parameter.

提交回复
热议问题