【问题标题】:Get json object from API, modify & post it using C#从 API 获取 json 对象,使用 C# 修改并发布它
【发布时间】:2020-04-25 12:19:38
【问题描述】:

下面是我的代码:

static void Main(string[] args)
{    
    SetBase();
    //Console.ReadLine();
}

public static async void SetBase()
{
    var baseAddress = new Uri("https://google.com/");
    var httpClient = new HttpClient { BaseAddress = baseAddress };
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
    var content = new StringContent("{ \"postUserLogin\":{ \"login\":\"username\", \"password\":\"password\", \"remember\":1,\"verify_level\":0 }}", System.Text.Encoding.Default, "application/json");
    try
    {
        var response = await httpClient.PostAsync("/account/login", content);

        using (var newresponse = await httpClient.GetAsync(viewURL + viewurlParameters))
        {
            if (newresponse.IsSuccessStatusCode)
            {                
                string responseData = await newresponse.Content.ReadAsStringAsync();
                JObject json = JObject.Parse(responseData);

                //Get input from User
                string input = Console.ReadLine();
                //Make changes to json object according to input                
                //And Post Json object
            }
        }
    }
    catch (Exception ex)
    {

    }
}

var response = await httpClient.PostAsync("/account/login", content); 之后的所有代码都不会被执行。

但是,如果我取消注释 Console.Readline() 中的 Main 行,其余步骤将被执行。请帮忙。

【问题讨论】:

  • 没有看到您写的内容,我们无法猜测问题或解决方案。您需要分享相关代码并解释您所面临的确切问题以及代码的预期行为和实际行为。
  • 我会在某个时候添加代码。谢谢。

标签: c# .net json visual-studio async-await


【解决方案1】:

是的,不要把它们放在一个循环中。请添加以后无法使用的代码,以免您的问题被删除。

按顺序做:

  1. 使用登录凭据调用 API 以获取令牌字符串
  2. 使用您的数据请求和令牌访问 API
  3. 如果要求注销 API,因为后续步骤可能需要很长时间
  4. 进行用户交互
  5. 将新项目添加到总列表
  6. 如果有新项目,请再次执行第 1 步
  7. 使用上传的数据和您的新令牌访问 API 端点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多