我对Web服务很新,尤其是WCF,所以请耐心等待。
我正在编写一个API,它接受一些参数,如username,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);
然后我可以读入。但是这会抛出一个错误,如果我想要一个流参数,它必须是唯一的参数。
那么我怎样才能实现我在这里要做的事情,或者在查询字符串中发送几千个单词没什么大不了的?
答案 0 :(得分:0)
我能找到的最佳答案解决了这个问题并为我工作,所以我可以正确地遵守RESTful标准
答案 1 :(得分: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;
}
答案 2 :(得分:-4)
只需使用WebServiceHostFactory
即可解决问题