Optional query string parameters in URITemplate in WCF?

只谈情不闲聊 提交于 2019-11-29 05:24:00
luksan

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/

Olly

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.

Check this blog post out. Makes sense to me, and comes with a class to parse out the query string parameters.

http://blogs.msdn.com/b/rjacobs/archive/2009/02/10/ambiguous-uritemplates-query-parameters-and-integration-testing.aspx

Basically don't define the query string parameters in the UriTemplate so it matches with/without the parameters, and use the sample class to retrieve them if they're there in the method implementation.

JOKe

Yes I can confirm after WCF 4.0 it works like a charm as described here WCF and optional parameters

This seems to work in WCF 4.0.
Just make sure to set your default value in your "Service1.svc.cs"

public string TestXml(string records)
{
  if (records == null)
      records = "10";

  //... rest of the code
}

While this is an old question, we still come to this scenario from time to time in recent projects.

To send optional query parameters, I created WCF Web Extensions nuget package.

After installation, you can use the package like this:

using (var factory = new WebChannelFactory<IQueryParametersTestService>(new WebHttpBinding()))
{
    factory.Endpoint.Address = new EndpointAddress(ServiceUri);
    factory.Endpoint.EndpointBehaviors.Add(new QueryParametersServiceBehavior());
    using (var client = factory.CreateWebChannel())
    {
        client.AddQueryParameter("format", "xml");
        client.AddQueryParameter("version", "2");
        var result = client.Channel.GetReport();
    }
}

Server side you can retrieve the parameters using WebOperationContext:

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