【问题标题】:How do I get the body of the POST request with WCF?如何使用 WCF 获取 POST 请求的正文?
【发布时间】:2021-02-08 14:20:28
【问题描述】:

我想用 WCF 获取 json 格式的 POST 请求的正文,下面是我的代码:

服务

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/GetBody", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
void GetBody(Stream stream);

客户端(使用restsharp)

var client = new RestClient("http://127.0.0.1");
var request = new RestRequest("/GetBody", Method.POST);
request.AddParameter("application/json", "{\"PortalType\":\"Merchant\"}", ParameterType.RequestBody);
var response = client.Execute(restRequest);

我收到以下错误:“StatusCode:BadRequest,Content-Type:text/html,Content-Length:2897)” 试了各种方法都没有成功,只能求助!

如果把客户端代码改成如下,那么就可以成功获取body了。

var client = new RestClient("http://127.0.0.1");
var request = new RestRequest("/GetBody", Method.POST);
//request.AddParameter("application/json", "{\"PortalType\":\"Merchant\"}", ParameterType.RequestBody);
requst.AddParameter("PortalType", "Merchant");
var response = client.Execute(restRequest);

【问题讨论】:

    标签: json .net wcf post request


    【解决方案1】:

    这是因为你的GetBody的请求参数是Stream类型的,而你在向WCF服务发送请求时将Content-Type设置为application/json,所以WCF服务会报bad request错误。

    当我们要发送一个Stream数据时,Content-Type应该是application/octet-stream,如果不设置Content-Type,Content-Type默认为application/octet -stream 传输Stream类型数据时。

    【讨论】:

      【解决方案2】:

      我找到了正确的解决方案。您需要设置 Web 服务的 ContentTypeMapper 以强制它使用 raw 来解析请求。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-02
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 2011-12-27
        • 2018-05-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多