我想阅读WCF Web服务收到的HttpRequest的主体。
WCF Web服务如下所示:
[ServiceContract]
public interface ITestRestService
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/test")]
string Test(Stream aStrm);
}
成功发送到此服务的客户端调用Test()
方法,但aStrm
引发异常:
'aStrm.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
我是否应该使用流来发送正文或其他内容?
当合同的配置如下所示,我可以将数据作为网址的一部分发送:
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "?s={aStr}")]
string Test(string aStr);
但是这是常见做法吗?我不应该逻辑地将内容添加到请求正文而不是网址吗?
答案 0 :(得分:1)
我同意你的看法,POST请求的主体是发送数据的更好地方。虽然一些Web服务确实通过URL发送数据。除了语义之外,如果敏感数据被发送,则存在安全问题,因为URL可以以纯文本等形式显示在管理日志中。
除非您确实需要大量数据的Stream
,否则您可以创建一个模型类来传输数据。早期版本的ASP.NET Web API(WCF Web API的后续版本)要求您为POST正文使用完整的类。
我会尝试像
这样的东西public class PostData
{
public string aStr { get; set; }
}
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "?s={aStr}")]
string Test(PostData data);
以下是有关使用WCF发布的参考资料。他演示了如何通过模型发布JSON数据。 http://blog.alexonasp.net/post/2011/05/03/REST-using-the-WCF-Web-API-e28093-POST-it!.aspx