Search code examples
jsonwcf

JSON Service passing empty/null string parameter value


I have set of WCF services which allow JSON format for message exchange.

[WebInvoke(Method = "GET", 
 ResponseFormat = WebMessageFormat.Json, 
 RequestFormat = WebMessageFormat.Json, 
 UriTemplate = "SearchStores/{accountId}/{storeName}")]
public IList<Store> SearchStores(string accountId, string storeName)

How can I pass an empty/null storeName to the method?

If I using following url to invoke the method, i get 404 not found error.

servername:port/myservice/SearchStores/1/

Solution

  • You could modify your template to use query string parameters instead.

    UriTemplate = "SearchStores?accountId={accountId}&storeName={storeName}"
    

    This way, accountId and storeName would be null if not specified in the query. If only storeName is allowed to be null, you could of course leave accountId as is and build the UriTemplate with a query string parameter for storeName.

    EDIT

    If you are not allowed to use the query string, then you can use a default null value in your UriTemplate as described in the MSDN UriTemplate documentation. In your case:

    UriTemplate = "SearchStores/{accountId}/{storeName=null}
    

    Note that once you use a default null value, all segments to the right must also have null default values. For instance, this would be valid:

    UriTemplate = "SearchStores/{accountId}/{storeName=null}/{someParam=null}
    

    But this would not:

    UriTemplate = "SearchStores/{accountId}/{storeName=null}/{someParam}