1

I've setup my service according to the latest tutorials I've found, and everything seems to work fine.

HOWEVER,

In order to access the WebOperationContext.Current.IncomingRequest.UriTemplateMatch class which contains the QueryParameters collection (e.g. ?name=tom&age=20), I need to have the service configured to use WebHttpBehavior. The only way I've managed to get this to work is to self host it using WebServiceHost from a console application. I can't get it to work from the web.config or global.asax from IIS or cassini.

I find it strange that tutorials on how to use the web-api talk about IoC before hosting the thing in IIS: wouldn't that be far more useful? They all seem to use extremely simple services that don't use query strings at all, with IoC!

Here are the resources I've found that almost mention the problem but don't fix it:

George
  • 1,964
  • 2
  • 19
  • 25
  • Why do you need access to the query params? – Alexander Zeitler Sep 08 '11 at 07:26
  • Because that's the only way to get them with the web-api? using the URITemplate lib doesn't work for optional parameters, and causes problems in general. Also I was following this: http://blogs.msdn.com/b/rjacobs/archive/2009/02/10/ambiguous-uritemplates-query-parameters-and-integration-testing.aspx – George Sep 08 '11 at 08:18
  • If you're asking why I need them in general...then so I can return resources with additional conditionals, like any REST service? – George Sep 08 '11 at 08:20
  • 1
    You are mixing old WCF and new Web API stuff. I'm pretty sure the IncomingRequest object is not used in Web API. – Darrel Miller Sep 08 '11 at 11:51

1 Answers1

3

You can do something like this:

[ServiceContract]
public class ContactResource {
    [WebGet(UriTemplate = "")]
    public HttpResponseMessage<Contact> Get(HttpRequestMessage request) {
        var querystring = request.RequestUri.Query;
        var parameters = HttpUtility.ParseQueryString(querystring);
        var name = parameters["Name"];
        return new HttpResponseMessage<Contact>(
            new Contact()
                {
                    Id = Guid.NewGuid(),
                    Name = name
                });
    }
}

http://localhost:12741/contact?name=George

yields:

<Contact>
<Id>19bae3a5-e2b7-4858-8aa4-08161ea18018</Id>
<Name>George</Name>
</Contact>
Alexander Zeitler
  • 11,919
  • 11
  • 81
  • 124