Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json 如何使用WCF获取POST请求的正文?_Json_.net_Wcf_Post_Request - Fatal编程技术网

Json 如何使用WCF获取POST请求的正文?

Json 如何使用WCF获取POST请求的正文?,json,.net,wcf,post,request,Json,.net,Wcf,Post,Request,我想用WCF获取json格式的POST请求主体,下面是我的代码: 服务 [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/GetBody", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] vo

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

服务

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

我得到以下错误:“状态代码:BadRequest,内容类型:text/html,内容长度:2897)” 我尝试了各种方法,但都没有成功,只能求助

如果客户机代码更改为以下代码,则可以成功获取主体

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);

这是因为GetBody的请求参数是Stream类型,并且在向WCF服务发送请求时将内容类型设置为application/json,因此WCF服务将报告错误的请求错误


当我们要发送流数据时,内容类型应为应用程序/八位字节流,如果您不设置内容类型,则在传输流类型数据时,内容类型默认为应用程序/八位字节流。

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

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);