400 Bad Request in POST to API

Viewed 100

I am trying to make a very simple WinForms application with JWT authorization. It takes the inputted values for video games from the user and, using POST, inserts it into my API that's connected to SQL. However, I keep getting the bad request error even though I went over the code numerous times. I tested the exact same POST request on Postman and it works just fine there.

private void btnPost_Click(object sender, EventArgs e)
{
    VideoGame videoGame = new VideoGame(
        tbName.Text, 
        tbGenres.Text, 
        tbPlatforms.Text, 
        tbPublisher.Text, 
        tbDeveloper.Text, 
        dtpReleaseDate.Value, 
        tbDesc.Text,
        nudPriceInEuro.Value);

    DataContractSerializer serialization = new DataContractSerializer(typeof(VideoGame));
    MemoryStream mStream = new MemoryStream();
    XmlWriter writer = XmlWriter.Create(mStream);
    serialization.WriteObject(writer, videoGame);
    writer.Close();

    byte[] serviceData = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(mStream.ToArray()));

    string key = *my key goes here*;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://localhost:5000/api/VideoGames");
    zahtjev.PreAuthenticate = true;
    zahtjev.Headers.Add("Authorization", key);
    zahtjev.Method = "POST";
    zahtjev.Accept = "application/xml";
    zahtjev.ContentType = "application/xml";
    Stream data = request.GetRequestStream();
    data.Write(serviceData, 0, serviceData.Length);
    data.Close();

    try
    {
        HttpWebResponse answer = (HttpWebResponse)request.GetResponse();
        Stream answerData = answer.GetResponseStream();

        DataContractSerializer deserialization = new DataContractSerializer(typeof(bool));
        bool successAdded = (bool)deserialization.ReadObject(answerData);

        if (successAdded)
        {
            lblSuccess.Text = "Success!";
        }
        else
        {
            lblSuccess.Text = "Unsuccessful!";
        }
    }
    catch (WebException ex)
    {
        using (var stream = ex.Response.GetResponseStream())
        using (var reader = new StreamReader(stream))
        {
            Console.WriteLine(reader.ReadToEnd());
        }
    }
}
0 Answers
Related