无法从HttpResponseMessage中的发布请求获取响应

时间:2020-01-02 06:41:52

标签: asp.net-mvc rest api httpresponsemessage

我阅读了很多问题,并测试了很多代码,但无法解决问题。 我想在ASP控制器中调用rest API(使用php代码编写)。

我用邮递员应用程序测试了我的Web服务,并从Web Service正确响应。但是我无法通过asp请求得到正确的答案。

我的问题:我得到状态码200用于响应(在asp控制器中),但是未执行Web服务上的指令(例如:请勿注册用户)。在哪里可以找到问题并获得答案中的数据?

 public async Task registerInShop()
    {
        try
        {
            ShopUserModel model = new ShopUserModel()
            {
                user_login = "ff",
                user_pass = "v12315",
                user_nicename = "",
                user_url = "",
                user_registered = "",
                user_activation_key = "",
                user_status = 0,
                display_name = "ff",
            };
            JsonResult json = Json(model, JsonRequestBehavior.AllowGet);
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("domainurl/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                HttpResponseMessage response = await client.PostAsJsonAsync("shopktphp/register.php", json.Data);
                response.EnsureSuccessStatusCode();
                if (response.IsSuccessStatusCode)
                {   // Get the URI of the created resource.  
                    Uri returnUrl = response.Headers.Location;
                    var res = response.Content;
                    Console.WriteLine(returnUrl);
                }
            }
        }
        catch (Exception ex)
        {
            Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(ex));
        }
    }

call Rest Api from Postman

1 个答案:

答案 0 :(得分:0)

我成功找到了问题的答案。我只更改基址的URI,并以此设置:“ domainurl / shopktphp /” 并通过“ register.php”设置Post json异步

client.BaseAddress = new Uri("domainurl/shopktphp/");

HttpResponseMessage response = await client.PostAsJsonAsync("register.php", json.Data);