【问题标题】:Reading HttpRequest Body in REST WCF在 REST WCF 中读取 HttpRequest 正文
【发布时间】:2011-03-04 06:26:09
【问题描述】:

我有一个在 .net 4 中运行的 REST WCF 服务,并且我已经测试了它正在运行的 Web 服务并接受了我向它发出的 HttpRequest。但是我在尝试访问 Web 服务中的 HttpRequest 正文时遇到了问题。我尝试使用 Fiddler 和我的 WinForm 应用程序发送附加在 HttpRequest 上的随机数据大小,但我似乎无法在运行时找到任何可以找到我的请求正文所在的对象。我最初的直觉是查看HttpContext.Current.Request.InputStream,但该属性的长度为0,因此我尝试查看IncomingWebRequestContext,该对象甚至没有获取HttpRequest主体的方法或属性。

所以我的问题是,真的有办法在 WCF 中访问 HttpRequest 请求正文吗?

PS: 请求正文中的数据是 JSON 字符串,对于响应,它也会将响应正文中的数据作为 JSON 字符串返回。

【问题讨论】:

    标签: json web-services .net-4.0 httprequest wcf-rest


    【解决方案1】:

    简单得多,WCF + REST: Where is the request data? 上的这个答案可以正常工作。

    另外,如果您的请求正文是可反序列化的,您可以只传递一个类。除非有一些错别字,否则应该可以:

    public class Banana
    {
        public string Colour;
        public int Size;
    }
    

    ...

    [WebInvoke(
        Method = "POST", 
        UriTemplate = "bananas", 
        ResponseFormat=WebMessageFormat.Json, 
        RequestFormat=WebMessageFormat.Json)]
    string CreateBanana(Banana banana);
    

    ...

    public string CreateBanana(Banana banana)
    {
        return "It's a " + banana.Colour + " banana!";
    }
    

    使用数据 {"Colour": "blue", "Size": 5} 对此资源执行 POST 应返回 "It's a blue banana!"

    【讨论】:

      【解决方案2】:

      试试((System.ServiceModel.Channels.BufferedMessageData)(((System.ServiceModel.Channels.BufferedMessage)((OperationContext.Current.RequestContext).RequestMessage)).MessageData)).Buffer

      它的类型为System.ArraySegment<byte>

      或阅读WCF + REST: Where is the request data?

      【讨论】:

      • 这是针对 .Net Framework 4.0 的吗?因为我在 System.ServiceModel.Channels 命名空间中找不到 BufferedMessageData 和 BufferedMessage
      • 我在 .Net Framework 4.0 WCF 项目的调试器(监视窗口)中使用了它。
      • 我什至已经将 System.ServiceModel 引用添加到我的项目中,但我仍然无法在 System.ServiceModel.Channels 中找到 BufferedMessageData 对象。我也尝试在对象浏览器中搜索它,但根本没有结果。
      • 您应该在调试器的“非公共成员”部分搜索。如果您想编写代码来访问数据,您应该获取System.ServiceModel.OperationContext.Current.RequestContext.RequestMessage 作为System.ServiceModel.Channels.Message 类型的实例,然后按照stackoverflow.com/questions/1850293/… 中描述的方式访问一些“非公共成员”。
      猜你喜欢
      • 2014-10-13
      • 1970-01-01
      • 2017-11-25
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 2011-01-12
      • 1970-01-01
      相关资源
      最近更新 更多