【问题标题】:How to POST a Json Object from c# client to Python API in the server?如何将 Json 对象从 c# 客户端发布到服务器中的 Python API?
【发布时间】:2018-10-12 13:13:40
【问题描述】:

我正在尝试将 JSON 数据从 C#(使用 JObject)发送到 Python Flask API。每当我在 localhost 中进行测试时,python API 都能够以 JSON 格式读取数据。但是当代码部署在服务器中时,它无法读取数据并且正在中断。 C# 代码部署在 Azure VM 的 IIS 中,Python 部署为 Azure 中的微服务。我究竟做错了什么?有没有其他方式可以在两种语言之间进行通信而不是 JSON。你可以在下面找到代码sn-ps:

C#:

string personjson = HttpContext.Request.Form["personinfo"]
var json = JObject.Parse(personjson);

_client = new HttpClient { BaseAddress = new 
Uri("http://mypythonapi.azurewebsites.net") };
_client.DefaultRequestHeaders.Clear();
_client.DefaultRequestHeaders.Accept.Clear();              
_client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

var response = await _client.PostAsJsonAsync("/insertPersonNode", 
json);
var message = response.IsSuccessStatusCode ? "Data posted" : $"Failed to post data. Status code:{response.StatusCode}";

Python:

@app.route('/insertPersonNode', methods=['POST'])
def insertPersonNode():
    try:        
        UserName = request.authorization['username']
        Password = request.authorization['password']
        userLoginNode = userAuthentication(UserName, Password)
        data = request.json 

【问题讨论】:

  • 能否提供错误详情?
  • 这就是问题所在,我无法在服务器日志中看到错误。我所知道的是它在读取数据时会中断。
  • 你试过在调试模式下运行它吗?
  • @Prometheus 是的,我尝试在调试模式下运行它,这是我得到的错误:400 Bad Request: The browser (or proxy) sent an request that this server could not understand.跨度>

标签: c# python json azure flask


【解决方案1】:

最后,我找到了解决这个问题的方法。使用 PostAsync 而不是 PostAsJsonAsync 对我有用。

var response = await _client.PostAsync("/insertPersonNode", new StringContent(personjson, Encoding.UTF8, "application/json"));

【讨论】:

    猜你喜欢
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2015-07-09
    • 2016-02-14
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    相关资源
    最近更新 更多