我已经实现了一个简单的自定义 QueryStringConverter 以便您可以将 qs1 设为 string[] 然后将查询字符串变量以逗号分隔(例如http://server/service/SomeRequest?qs1=val1,val2,val3,val4)
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml,
UriTemplate = "SomeRequest?qs1={qs1}")]
XElement SomeRequest2(string[] qs1);
首先,您需要一个继承自 WebHttpBehavior 的类,以便我们可以注入我们的自定义 QueryStringConverter:
public class CustomHttpBehavior : System.ServiceModel.Description.WebHttpBehavior
{
protected override System.ServiceModel.Dispatcher.QueryStringConverter GetQueryStringConverter(System.ServiceModel.Description.OperationDescription operationDescription)
{
return new CustomQueryStringConverter();
}
}
然后是处理 string[] 参数的 CustomQueryStringConverter:
public class CustomQueryStringConverter : System.ServiceModel.Dispatcher.QueryStringConverter
{
public override bool CanConvert(Type type)
{
if (type == typeof(string[]))
{
return true;
}
return base.CanConvert(type);
}
public override object ConvertStringToValue(string parameter, Type parameterType)
{
if (parameterType == typeof(string[]))
{
string[] parms = parameter.Split(',');
return parms;
}
return base.ConvertStringToValue(parameter, parameterType);
}
public override string ConvertValueToString(object parameter, Type parameterType)
{
if (parameterType == typeof(string[]))
{
string valstring = string.Join(",", parameter as string[]);
return valstring;
}
return base.ConvertValueToString(parameter, parameterType);
}
}
您需要做的最后一件事是创建行为配置扩展,以便运行时可以获取 CustomWebHttpBehavior 的实例:
public class CustomHttpBehaviorExtensionElement : System.ServiceModel.Configuration.BehaviorExtensionElement
{
protected override object CreateBehavior()
{
return new CustomHttpBehavior();
}
public override Type BehaviorType
{
get { return typeof(CustomHttpBehavior); }
}
}
现在我们将元素添加到我们的配置扩展中,以便使用我们的 CustomWebHttpBehavior,我们使用该扩展的名称而不是<webHttp />
我们的行为:
<system.serviceModel>
<services>
<service name="NameSpace.ServiceClass">
<endpoint address="" behaviorConfiguration="MyServiceBehavior"
binding="webHttpBinding" contract="NameSpace.ServiceClass" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="MyServiceBehavior">
<customWebHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="customWebHttp" type="NameSpace.CustomHttpBehaviorExtensionElement, MyAssemblyName" />
</behaviorExtensions>
</extensions>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
您现在还可以扩展您的 CustomQueryStringConverter 以处理默认类型不处理的其他类型,例如可为空的值类型。
注意:在 microsoft connect 中记录了一个与此代码直接相关的错误。在您尝试查询转换不同类型的几乎所有情况下,该代码实际上并不适用。
http://connect.microsoft.com/VisualStudio/feedback/details/616486/bug-with-getquerystringconverter-not-being-called-by-webservicehost#tabs
请确保在浪费时间创建无法正常工作的自定义 REST 查询字符串转换器之前仔细阅读此内容。(适用于 Framework 4.0 及以下版本)。