Using the WCF HTTP Web API, UriTemplateMatch is always null

回眸只為那壹抹淺笑 提交于 2019-12-23 01:20:12

问题


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:

  • http://social.msdn.microsoft.com/Forums/nl-NL/wcf/thread/33861d74-9037-4d4f-836b-efe715de5af3
  • http://pfelix.wordpress.com/2011/04/22/wcf-web-apiiis-hosting/

回答1:


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>


来源:https://stackoverflow.com/questions/7344478/using-the-wcf-http-web-api-uritemplatematch-is-always-null

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