Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional query string parameters in URITemplate in WCF?

I'm developing some RESTful services in WCF 4.0. I've got a method as below:

[OperationContract]     [WebGet(UriTemplate = "Test?format=XML&records={records}", ResponseFormat=WebMessageFormat.Xml)]     public string TestXml(string records)     {         return "Hello XML";     } 

So if i navigate my browser to http://localhost:8000/Service/Test?format=XML&records=10, then everything works as exepcted.

HOWEVER, i want to be able to navigate to http://localhost:8000/Service/Test?format=XML and leave off the "&records=10" portion of the URL. But now, I get a service error since the URI doesn't match the expected URI template.

So how do I implement defaults for some of my query string parameters? I want to default the "records" to 10 for instance if that part is left off the query string.

like image 768
Shafique Avatar asked Jun 03 '10 19:06

Shafique


People also ask

Can query parameters be optional?

As query parameters are not a fixed part of a path, they can be optional and can have default values.

What is UriTemplate in WCF?

UriTemplate is a class that encapsulates a URI template. The constructor takes a string parameter that defines the template. This string contains the template in the format described in the next section.

What is WebInvoke method in WCF?

The WebInvoke attribute exposes services using other HTTP verbs such as POST, PUT, and DELETE. The default is to use POST, but it can be changed by setting the Method property of the attribute. These operations are meant to modify resources; therefore, the WebInvoke attribute is used to make modifications to resources.


2 Answers

Note: This question is out of date, please see the other answers.


This does not appear to be supported.

However, Microsoft has been made aware of this issue and there is a work-around:

You can get the desired effect by omitting the Query string from the UriTemplate on your WebGet or WebInvoke attribute, and using WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters from within your handlers to inspect, set defaults, etc. on the query parameters.

https://connect.microsoft.com/VisualStudio/feedback/details/451296/

like image 123
luksan Avatar answered Sep 22 '22 05:09

luksan


According to this answer this is fixed in .NET 4.0. Failing to supply the query string parameter seems to result in its being given the default value for the type.

like image 43
Olly Avatar answered Sep 21 '22 05:09

Olly