带有查询字符串参数和帖子正文的 WCF WebInvoke

问题描述 投票:0回答:4

我对 Web 服务尤其是 WCF 还很陌生,所以请耐心等待。

我正在编写一个 API,它需要几个参数,例如用户名、apikey 和一些选项,但我还需要向它发送一个可能有几千个单词的字符串,该字符串会被操作并作为流传回。仅将其放入查询字符串中是没有意义的,所以我想我只需将消息正文发布到服务即可。

似乎没有一个简单的方法可以做到这一点...

我的运营合同是这样的

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate="Method1?email={email}&apikey={apikey}"+
"&text={text}&quality={qual}", BodyStyle = WebMessageBodyStyle.Bare)]
Stream Method1(string email, string apikey, string text, string qual);

这有效。但这是我想提取并包含在帖子正文中的“文本”参数。我读到的一件事说有一个流作为另一个参数,如下所示:

Stream Method1(string email, string apikey, string qual, Stream text);

然后我可以读入。但这会引发一个错误,指出如果我想要一个流参数,它必须是唯一的参数。

那么我怎样才能实现我在这里想要做的事情,或者在查询字符串中发送几千个单词没什么大不了的?

wcf post webinvoke
4个回答
0
投票

https://social.msdn.microsoft.com/Forums/vstudio/en-US/e2d074aa-c3a6-4e78-bd88-0b9d24b561d1/how-to-declare-post-parameters-in-wcf-rest-contract?论坛=wcf

我能找到的最佳答案可以解决这个问题并对我有用,这样我就可以正确遵守 RESTful 标准


0
投票

解决方法是不在方法签名中声明查询参数,而只是从原始 uri 中手动提取它们。

Dictionary<string, string> queryParameters = WcfUtils.QueryParameters();
queryParameters.TryGetValue("email", out string email);


// (Inside WcfUtils):

public static Dictionary<string, string> QueryParameters()
{
    // raw url including the query parameters
    string uri = WebOperationContext.Current.IncomingRequest.UriTemplateMatch;

    return uri.Split('?')
        .Skip(1)
        .SelectMany(s => s.Split('&'))
        .Select(pv => pv.Split('='))
        .Where(pv => pv.Length == 2)
        .ToDictionary(pv => pv[0], pv => pv[1].TrimSingleQuotes());
}

// (Inside string extension methods)

public static string TrimSingleQuotes(this string s)
{
    return (s != null && s.Length >= 2 && s[0] == '\'' && s[s.Length - 1] == '\'')
        ? s.Substring(1, s.Length - 2).Replace("''", "'")
        : s;
}

0
投票

如果你想在参数中使用 Stream,但又想传递 string 或 int,那么此时你需要创建一个类,在该类中你可以传递你想要发送的内容,然后将该类调用到你的参数中。 如有任何疑问,请随时询问。

谢谢 丹麦沙菲克


-5
投票

最终通过使用 WebServiceHostFactory 简单地解决了问题

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.