Home > Back-end >  am trying to make a post request to an API on an internal server using ASP. Net core ,I receive inte
am trying to make a post request to an API on an internal server using ASP. Net core ,I receive inte

Time:09-21

this is the json body I send using postman and it works (API respond is Boolean so I get true in this case. )

{ "ClubID":"A9FEE6F-FBBB-EB11","ContactID":"B6F1-43A48402F","LoginDate":"2017-11-19T22:00:00 2"}

and that is the function am trying to use to make the post request and get the respond back.

     var http = (HttpWebRequest)WebRequest.Create(url);
            http.Accept = "application/json";
            http.ContentType = "application/json";
http.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; "  
                                  "Windows NT 5.2; .NET CLR 1.0.3705;)");
        http.Method = "POST";
        String json = Newtonsoft.Json.JsonConvert.SerializeObject(listOfMem);
        UTF8Encoding encoding = new UTF8Encoding();
        Byte[] bytes = encoding.GetBytes(json);

        Stream newStream = http.GetRequestStream();
        newStream.Write(bytes, 0, bytes.Length);
        newStream.Close();

        var response = await http.GetResponseAsync();

        var stream = response.GetResponseStream();
        var sr = new StreamReader(stream);
        var content = sr.ReadToEnd();
        string res = content.ToString();
        

CodePudding user response:

Since we using .net core, please drop off using of the acient HttpWebRequest, let he rest in peace...

this template should work

// A class that hold the request
public class MyHttpRequestData
{
    public string ClubID { get; set; }
    public string ContactID { get; set; }
    public DateTime LoginDate { get; set; }
}

// Request
var myContent = new MyHttpRequestData(); // Initialize
using var request = new HttpRequestMessage
{
    Content = new StringContent(JsonSerializer.Serialize(myContent), Encoding.UTF8, "application/json"),
    Method = HttpMethod.Post,
    RequestUri = new Uri("Url goes here!")
};
using var httpClient = new HttpClient();
using var response = await httpClient.SendAsync(request);
// do whatever it is with the response

CodePudding user response:

To post JSON data to your API endpoint, you can also try the following code snippet.

using System.Net.Http;
using System.Net.Http.Json;

using enter image description here

enter image description here

  • Related