在我的REST WCF服务中,我传递了将近15个参数。我像这样在URL中传递这些参数:
www.mysite.com/wcfservice/mymethod/{p1},{p2},{p3},{p4}...有没有更好的传递参数的方法?在URL中传递参数是否会导致任何安全问题(如SQL注入)?使用XML文件传递参数是否明智?在REST WCF服务中传递参数的最佳方式是什么?
发布于 2011-10-04 23:38:58
假设您的方法是Idempotent (即GET),似乎您知道不能使用body进行传输。所以剩下的就是URL和头了。
将与此特定请求无关的信息放入标头中-例如,您的ProtocolVersion、SystemName -并在服务中解析这些标头。
在URL中放入那些上下文相关的参数,这些参数是执行操作所必需的:例如EntityId、FilterValue。
如果你正在传递一个参数的列表--例如value1=1,2,3 --那么你可以考虑使用一个自定义的QueryString转换器(见下文--将行为附加到端点是另一个练习)。
最后,你可能只需要传递那么多的参数。这对于基于搜索的操作是非常常见的,其中可能有不同的维度进行搜索。
using System;
using System.Linq;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
public class CustomQueryStringConverter : QueryStringConverter
{
public override bool CanConvert(Type type)
{
return base.CanConvert(type.IsArray ? type.GetElementType() : type);
}
public override object ConvertStringToValue(string parameter, Type parameterType)
{
object result = null;
if (parameterType.IsArray)
{
if (!ReferenceEquals(parameter, null))
{
object[] items = parameter
.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Where(s => !string.IsNullOrWhiteSpace(s))
.Select(s => base.ConvertStringToValue(s.Trim(), parameterType.GetElementType()))
.ToArray();
Array arrayResult = Array.CreateInstance(parameterType.GetElementType(), items.Length);
for (int i = 0; i < items.Length; ++i)
{
arrayResult.SetValue(items[i], i);
}
result = arrayResult;
}
}
else
{
result = base.ConvertStringToValue(parameter, parameterType);
}
return result;
}
public override string ConvertValueToString(object parameter, Type parameterType)
{
string result = string.Empty;
if (parameterType.IsArray)
{
foreach (object item in (Array)parameter)
{
result += item.ToString() + ",";
}
result = result.TrimEnd(',');
}
else
{
result = base.ConvertValueToString(parameter, parameterType);
}
return result;
}
public class CustomQueryStringBehavior : WebHttpBehavior
{
protected override QueryStringConverter GetQueryStringConverter(OperationDescription operationDescription)
{
return new CustomQueryStringConverter();
}
}
}https://stackoverflow.com/questions/7338703
复制相似问题