Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
WCF中URITemplate中的可选查询字符串参数?_Wcf_Query String_Uri_Uritemplate - Fatal编程技术网

WCF中URITemplate中的可选查询字符串参数?

WCF中URITemplate中的可选查询字符串参数?,wcf,query-string,uri,uritemplate,Wcf,Query String,Uri,Uritemplate,我正在WCF4.0中开发一些RESTful服务。我有一个方法如下: [OperationContract] [WebGet(UriTemplate = "Test?format=XML&records={records}", ResponseFormat=WebMessageFormat.Xml)] public string TestXml(string records) { return "Hello XML"; } 因此,如果我将浏

我正在WCF4.0中开发一些RESTful服务。我有一个方法如下:

[OperationContract]
    [WebGet(UriTemplate = "Test?format=XML&records={records}", ResponseFormat=WebMessageFormat.Xml)]
    public string TestXml(string records)
    {
        return "Hello XML";
    }
因此,如果我将浏览器导航到,那么一切都将正常工作

但是,我希望能够导航到URL的“&records=10”部分并将其删除。但是现在,我得到了一个服务错误,因为URI与预期的URI模板不匹配


那么,如何实现一些查询字符串参数的默认值呢?我想将“记录”默认为10,例如,如果查询字符串中没有该部分。

注意:此问题已过时,请参阅其他答案。


这似乎不受支持

然而,微软已经意识到了这个问题,并且有一个解决办法:

你可以通过以下方法获得想要的效果 将查询字符串从 在您的WebGet或 WebInvoke属性,并使用 WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters 从处理程序内部进行检查, 设置查询的默认值等 参数


查看此博客帖子。这对我来说很有意义,并且附带了一个类来解析查询字符串参数


基本上,不在UriTemplate中定义查询字符串参数,以便它与参数匹配/不匹配,如果它们在方法实现中,则使用示例类来检索它们。

根据这一点,在.NET 4.0中是固定的。未能提供查询字符串参数似乎会导致为其指定类型的默认值。

这似乎在WCF 4.0中起作用。
只需确保在“Service1.svc.cs”中设置默认值


虽然这是一个老问题,但在最近的项目中,我们仍不时会遇到这种情况

为了发送可选的查询参数,我创建了nuget包

安装后,您可以使用以下软件包:

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();
    }
}

因此,这似乎效果良好。但是,如果我尝试针对此运行单元测试,它将不再有效,因为单元测试没有WebOperationContext。我查了几个例子,但是有没有人能举一个简单的例子来模拟WebOperationContext?试试谷歌搜索“mock WebOperationContext”。关于如何做到这一点,有很多不同的想法。
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();
    }
}
WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters;