2011-09-07 216 views
2

在我的REST WCF服务中,我传递了近15个参数。我通过这些参数在这样的URL:在Rest Wcf服务中传递参数

www.mysite.com/wcfservice/mymethod/{p1},{p2},{p3},{p4}... 

有没有更好的方式传递参数?在URL中传递参数是否会导致任何安全问题(如SQL注入)?使用XML文件传递参数是否明智?在REST WCF服务中传递资源的最佳方式是什么?

+4

为什么不使用Post和像Json这样的数据传输格式。 Xml也很好,但Json通常更好。 –

+0

不是很好的uri模板。一些标准验证应该防止任何SQL注入。我同意最好将某些媒体作为json或xml发送,并调整uri模板。另外一个设计问题是P1,...,pi相关 - 他们是否一起构建了一个对象?如果是这样 - 你还有一个重新设计的理由。 –

+0

嗨doc - 我使用POST方法只发布这些参数 – Henry

回答

1

假设你的方法是Idempotent(即GET),看起来你知道你不能使用身体进行转移。所以你留下的URL和头。

在标题中放入与上述特定请求不相关的信息 - 例如,您的ProtocolVersion,SystemName - 并解析服务中的这些标头。

在URL中放置了上下文相关的参数,这些参数是您执行操作所必需的:例如, EntityId,FilterValue。

如果您传递一个参数的列表 - 例如value1 = 1,2,3 - 那么你可以考虑使用一个自定义的QueryString转换器(见下面 - 将行为附加到Endpoint是另一个练习)。

最后,您可能只需要传递许多参数。基于搜索的操作非常普遍,其中可能有多种维度可供搜索。

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

    } 

}