我想知道如何使用:
string limit = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["Limit"];
在我这个方法WCF:
CityNewsList GetNewsByCity(string DeviceType,string id,string limit);
这里“设备类型”和“ID”是默认的参数,我想的是“限制”作为可选参数意味着用户有选择地通过这个参数,他可以通过或不能通过此。
要使用限制为:
if (limit == some value)
{
//do this.
}
if (limit == null)
{
// do this.
}
我要经过许多环节,但我没有得到这如何在我的WCF使用。
或者,如果有人能告诉我如何做一个参数的WCF服务可选。
所以实际上你使用WCF创建一个REST的服务。 我读过你的答案,你要创建的可能重复的问题是什么意思: 如何在WCF REST服务可选参数?
您可以省略对你WebGet或WebInvoke属性从UriTemplate查询字符串,并使用获得预期的效果WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters
。
那么,什么是会下来的是:
更改方法的签名,以省略该参数:
CityNewsList GetNewsByCity(string DeviceType,string id /*,string limit*/);
更改属性,以便不预期参数的查询字符串:
[OperationContract]
[WebGet(UriTemplate = "/whatever/{DeviceType}/{id}", RequestFormat = WebMessageFormat.Xml)]
代替
[OperationContract]
[WebGet(UriTemplate = "/whatever/{DeviceType}/{id}/{limit}", RequestFormat = WebMessageFormat.Xml)]
最后,你会碰到这样的:
[OperationContract]
[WebGet(UriTemplate = "/whatever/{DeviceType}/{id}", RequestFormat = WebMessageFormat.Xml)]
CityNewsList GetNewsByCity(string DeviceType,string id);
而实现的首先要做的事情是:
string limit = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["Limit"];
但是:我还没有尝试过,但是这就是我从你的意见,你的问题已经报什么了解。
一个最近也有类似的问题,并通过覆盖默认QueryStringConverter解决它。
1)子类System.ServiceModel.Dispatcher.QueryStringConverter并覆盖其ConvertStringToValue方法。
例如,使所有枚举可选的(如果没有值默认值将被使用)
public override object ConvertStringToValue(string parameter, Type parameterType)
{
if (parameterType.IsEnum)
{
if (string.IsNullOrEmpty(parameter))
{
return Activator.CreateInstance(parameterType);
}
}
return base.ConvertStringToValue(parameter, parameterType);
}
2)子类System.ServiceModel.Description.WebHttpBehavior并覆盖其GetQueryStringConverter方法来回报您的修改查询字符串转换器
public class ExtendedQueryStringBehavior : WebHttpBehavior
{
protected override QueryStringConverter GetQueryStringConverter(OperationDescription operationDescription)
{
return new ExtendedQueryStringConverter();
}
}
3)胡克新WebHttpBehavior到期望的终点(可能需要合并与你可能有其他的东西)这个功能。
人们可以支持与QS转换器相当复杂的场景,复杂的类型,CSV列表,数组等等。一切都将是强类型,并从单点转换管理 - 无需应对在服务/方法级解析噩梦。
我解决了可选/默认问题的方法是
Interface.cs:(您设置可选参数有默认{X = Y})
[OperationContract]
[WebGet(UriTemplate = "draw/{_objectName}/{_howMany}/{_how=AnyWay}"
, ResponseFormat = WebMessageFormat.Json
)]
YourShape[] doDraw(string _objectName, string _howMany, string _how);
method.svc.cs:(测试X ==默认情况下:X)
YourShape[] doDraw(string _objectName, string _howMany, string _how) {
if (_how == "AnyWay")
_how = findTheRightWay();
return (drawShapes(_objectName, _howMany, _how));
}
您的端点可以是
yoursite/draw/circle/5
要么
yoursite/draw/circle/5/ThisWay