C# Web API Sending Body Data in HTTP Post REST Client

a 夏天 提交于 2020-01-03 08:32:07

问题


I need to send this HTTP Post Request:

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

 {"Password":"password",
 "AppVersion":"1",
 "AppComments":"",
 "UserName":"username",
 "AppKey":"dakey" 
  }

It works great in RestClient and PostMan just like above.

I need to have this pro-grammatically and am not sure if to use

WebClient, HTTPRequest or WebRequest to accomplish this.

The problem is how to format the Body Content and send it above with the request.

Here is where I am with example code for 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;
    }

This DOES NOW WORK and responses with a (200) OK Server and Response


回答1:


Why are you generating you own json?

Use JSONConvert from JsonNewtonsoft.

Your json object string values need " " quotes and ,

I'd use http client for Posting, not webclient.

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());
   }
}   



回答2:


You are not properly serializing your values to JSON before sending. Instead of trying to build the string yourself, you should use a library like JSON.Net.

You could get the correct string doing something like this:

var message = JsonConvert.SerializeObject(new {Password = pw, AppVersion = apv, AppComments = acm, UserName = user, AppKey = apk});
Console.WriteLine(message); //Output: {"Password":"password","AppVersion":"10","AppComments":"","UserName":"username","AppKey":"dakey"}



回答3:


we will use HttpPost with HttpClient PostAsync for the issue.

using System.Net.Http;
    static async Task<string> PostURI(Uri u, HttpContent c)
    {
    var response = string.Empty;
    using (var client = new HttpClient())
    {
    HttpResponseMessage result = await client.PostAsync(u, c);
    if (result.IsSuccessStatusCode)
    {
    response = result.StatusCode.ToString();
    }
    }
    return response;
    }

We will call it by creating a string that we will use to post:

  Uri u = new Uri("http://localhost:31404/Api/Customers");
        var payload = "{\"CustomerId\": 5,\"CustomerName\": \"Pepsi\"}";

        HttpContent c = new StringContent(payload, Encoding.UTF8, "application/json");
        var t = Task.Run(() => PostURI(u, c));
        t.Wait();

        Console.WriteLine(t.Result);
        Console.ReadLine();


来源:https://stackoverflow.com/questions/50458507/c-sharp-web-api-sending-body-data-in-http-post-rest-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!