0

In AngularJs I could easily post data to an url by

$http.post(url, data)

data here is an array something like this :

["test1","test2","test3"]

My question is how can I do the same thing in C#? I want to use HttpWebRequest.

Arc676
  • 4,445
  • 3
  • 28
  • 44
Todd Liang
  • 85
  • 1
  • 9

2 Answers2

0

Use ToList on your array and FormUrlEncodedContent for your post request, see below

 using System.Net.Http;

 data.ToList(); //your data, assuming it is already a well-formed array or data model

 var content = new FormUrlEncodedContent(values);

 var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

 var responseString = await response.Content.ReadAsStringAsync();
0

Actually I found the answer myself.

payload here can be an array :

var request = (HttpWebRequest)WebRequest.Create(url);

        request.ContentType = "application/json";
        request.Method = action;


        JsonSerializerSettings serializerSettings = new JsonSerializerSettings
        {
            ContractResolver = new UnderscoreMappingResolver(),
            Formatting = Formatting.None,
            NullValueHandling = NullValueHandling.Ignore,
            Converters =
                {
                    new IsoDateTimeConverter
                    {
                        DateTimeStyles = DateTimeStyles.RoundtripKind
                    },
                    new StringEnumConverter
                    {
                        CamelCaseText = true
                    }
                }
        };

        var json = JsonConvert.SerializeObject(payload, serializerSettings);
        request.ContentLength = json.Length;

        Console.Out.Write(request.RequestUri);

        using (var stream = request.GetRequestStream())
        {
            using (var sw = new StreamWriter(stream))
            {
                sw.Write(json);
            }
        }

        HttpWebResponse response;

        try
        {
            response = request.GetResponse() as HttpWebResponse;
        }
        catch (WebException ex)
        {
            response = ex.Response as HttpWebResponse;
        }
Todd Liang
  • 85
  • 1
  • 9