gpt4 book ai didi

c# - CURL 到 WCF 的更好方法

转载 作者:搜寻专家 更新时间:2023-10-31 21:31:04 25 4
gpt4 key购买 nike

我可以通过 CURL 请求从 PHP 发布到我用 C# 编写的 Web 服务,但我无法让请求正确通过。无论我做什么,让帖子显示的唯一方法是 json_encode 表单数据标题。所以我的 PHP 代码最终是这样的:

$user = array('id'=>5, 'first_name' => 'First', 'last_name' => 'Last');$uch = curl_init();curl_setopt($uch, CURLOPT_URL,"http://localhost:50115/Service1.svc/postUser");curl_setopt($uch, CURLOPT_POST, 1);curl_setopt($uch, CURLOPT_POSTFIELDS, json_encode("user=" . json_encode($user)));curl_setopt($uch, CURLOPT_HTTPHEADER, array(                                            'Content-Type: application/json'                                            ));curl_setopt($uch, CURLOPT_RETURNTRANSFER, true);$response = curl_exec($uch);

When I set the line:

curl_setopt($uch, CURLOPT_POSTFIELDS, json_encode("user=" . json_encode($user)));

到:

curl_setopt($uch, CURLOPT_POSTFIELDS, array("user" => json_encode($user)));
--OR--
curl_setopt($uch, CURLOPT_POSTFIELDS,
http_build_query(array("user" => json_encode($user))));
--OR--
curl_setopt($uch, CURLOPT_POSTFIELDS, json_encode($user));

PHP 中没有错误,C# 服务没有返回错误(我确实在配置中设置了返回异常设置),并且函数上的断点永远不会被击中。

在 C# 方面,我的界面和服务设置如下:

//Interface[OperationContract][WebInvoke(Method="POST",            BodyStyle=WebMessageBodyStyle.Bare, //Any other value, the break-point                                                 //will not trigger            RequestFormat=WebMessageFormat.Json,            UriTemplate = "postUser")]void PostUser(string user);//Servicepublic void PostUser(string user){    var request = user;    int i = 5; //Debug set here}

When the break-point hits, I am able to see that user has the value of:

user={"id":5,"first_name":"First","last_name":"Last"}

我想要的是 user 的值只是:

{"id":5,"first_name":"First","last_name":"Last"}

是否可以收到我这样的回复?如果是这样,我需要更改什么才能实现它?

最佳答案

在 PHP 和 C# 中尝试了多种组合后,我终于让它工作了。在 PHP 中,CURLOPT_POSTFIELDS 需要设置为:

curl_setopt($uch, CURLOPT_POSTFIELDS, json_encode(array("user" => json_encode($user))));

然后,在 C# 中,我需要将 BodyStyle=WebMessageBodyStyle.Bare 更改为 BodyStyle=WebMessageBodyStyle.Wrapped

关于c# - CURL 到 WCF 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30007305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com