简体   繁体   English

如何读取HttpRequest,WCF的正文

[英]How to read body of HttpRequest, WCF

I want to read the body of a HttpRequest received by a WCF web service. 我想阅读WCF Web服务收到的HttpRequest的正文。

The WCF web service looks like so: WCF Web服务如下所示:

[ServiceContract]
public interface ITestRestService
{
    [OperationContract]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "/test")]
    string Test(Stream aStrm);
}

The client that sends to this service successfully invokes the Test() method but the aStrm throws an exception: 发送给该服务的客户端成功调用了Test()方法,但是aStrm引发了异常:

'aStrm.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

Should I be using the stream to send the body or something else? 我应该使用流来发送正文或其他内容吗?

I can send the data as part of the url when the configs for that contract look like so: 当该合同的配置如下所示时,我可以将数据作为url的一部分发送:

    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "?s={aStr}")]
    string Test(string aStr);

but is this common practice? 但这是惯例吗? shouldn't I logically be adding the content to the body of the request instead of the url? 我是否应该在逻辑上将内容添加到请求的正文而不是url?

I've read similar questions but I'm still uncertain. 我读过类似的 问题,但仍不确定。

I agree with you that the body of the POST request is a better place to send the data. 我同意您的观点,POST请求的正文是发送数据的更好位置。 Though some web services do send data via the url instead. 尽管某些Web服务确实通过url发送数据。 Apart from semantics there are security concerns if sensitive data is sent as url's can show up in administrative logs in plain text, etc. 除了语义外,是否还会发送安全性数据,因为发送的敏感数据会以纯文本等形式显示在管理日志中,因此会发送url。

Unless you really need a Stream for large amounts of data, you can create a model class to transport the data. 除非确实需要大量数据Stream ,否则可以创建一个模型类来传输数据。 Earlier versions of ASP.NET Web API (the successor of WCF Web API) required you to use a full class for the POST body. 早期版本的ASP.NET Web API (WCF Web API的后继版本)要求您对POST正文使用完整的类。

I would try something like 我会尝试像

public class PostData
{
    public string aStr { get; set; }
}

[WebInvoke(Method = "POST",
 ResponseFormat = WebMessageFormat.Json,
 BodyStyle = WebMessageBodyStyle.Bare,
 UriTemplate = "?s={aStr}")]
    string Test(PostData data);

Here is a reference you can use regarding Posting with WCF. 这是有关使用WCF进行发布的参考。 He demonstrates posting JSON data via a model. 他演示了通过模型发布JSON数据。 http://blog.alexonasp.net/post/2011/05/03/REST-using-the-WCF-Web-API-e28093-POST-it!.aspx http://blog.alexonasp.net/post/2011/05/03/REST-using-the-WCF-Web-API-e28093-POST-it!.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM