C#Web API在HTTP Post REST客户端中发送正文数据

Cra*_*Ste 7 c# asp.net-web-api advanced-rest-client asp.net-core

我需要发送以下HTTP发布请求:

 POST https://webapi.com/baseurl/login
 Content-Type: application/json

 {"Password":"password",
 "AppVersion":"1",
 "AppComments":"",
 "UserName":"username",
 "AppKey":"dakey" 
  }
Run Code Online (Sandbox Code Playgroud)

就像上面一样,它在RestClient和PostMan中也很好用。

我需要在语法上做到这一点,并且不确定是否要使用

WebClient,HTTPRequest或WebRequest可以完成此任务。

问题是如何格式化正文内容并在请求中将其发送到上方。

这是我使用WebClient的示例代码的地方...

  private static void Main(string[] args)
    {
        RunPostAsync();
    } 

    static HttpClient client = new HttpClient();

    private static void RunPostAsync(){

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            Inputs inputs = new Inputs();

            inputs.Password = "pw";
            inputs.AppVersion = "apv";
            inputs.AppComments = "apc";
            inputs.UserName = "user";
            inputs.AppKey = "apk";


            var res = client.PostAsync("https://baseuriplus", new StringContent(JsonConvert.SerializeObject(inputs)));

            try
            {
                res.Result.EnsureSuccessStatusCode();

                Console.WriteLine("Response " + res.Result.Content.ReadAsStringAsync().Result + Environment.NewLine);

            }
            catch (Exception ex)
            {
                Console.WriteLine("Error " + res + " Error " + 
                ex.ToString());
            }

        Console.WriteLine("Response: {0}", result);
    }       

    public class Inputs
    {
        public string Password;
        public string AppVersion;
        public string AppComments;
        public string UserName;
        public string AppKey;
    }
Run Code Online (Sandbox Code Playgroud)

现在就可以使用(200)OK服务器和响应了

Ya *_*ang 8

为什么要生成自己的json?

JSONConvert从 JsonNewtonsoft使用。

您的 json 对象字符串值需要" "引号和,

我会使用 http 客户端进行发布,而不是 web 客户端。

using (var client = new HttpClient())
{
   var res = client.PostAsync("YOUR URL", 
     new StringContent(JsonConvert.SerializeObject(
       new { OBJECT DEF HERE },
       Encoding.UTF8, "application/json")
   );

   try
   {
      res.Result.EnsureSuccessStatusCode();
   } 
   catch (Exception e)
   {
     Console.WriteLine(e.ToString());
   }
}   
Run Code Online (Sandbox Code Playgroud)

  • 上面发布了此代码的工作版本供我使用。不需要 StringContent 参数。谢谢@Ya (2认同)