首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Rest Wcf服务中传递参数

在Rest Wcf服务中传递参数
EN

Stack Overflow用户
提问于 2011-09-08 02:25:53
回答 1查看 3.1K关注 0票数 2

在我的REST WCF服务中,我传递了将近15个参数。我像这样在URL中传递这些参数:

代码语言:javascript
复制
www.mysite.com/wcfservice/mymethod/{p1},{p2},{p3},{p4}...

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

EN

回答 1

Stack Overflow用户

发布于 2011-10-04 23:38:58

假设您的方法是Idempotent (即GET),似乎您知道不能使用body进行传输。所以剩下的就是URL和头了。

将与此特定请求无关的信息放入标头中-例如,您的ProtocolVersion、SystemName -并在服务中解析这些标头。

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

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

最后,你可能只需要传递那么多的参数。这对于基于搜索的操作是非常常见的,其中可能有不同的维度进行搜索。

代码语言:javascript
复制
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();
        }

    }

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7338703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档