Click here to Skip to main content
15,040,212 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am getting
The remote server returned an error: (500) Internal Server Error
when trying to call a REST API in Web Application using asp.net C#.

I have use try &
catch (WebException ex)
but i am getting blank message in exception response

What I have tried:

string URL = "Sample Url";
           string DATA = @"{""object"":{""name"":""Name""}}";

           HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
           request.Method = "POST";
           request.Headers["Authentication"] = "Bearer MyKEYVALUE";

           request.ContentType = "application/json; charset=utf-8";
           request.ContentLength = DATA.Length;
           using (Stream webStream = request.GetRequestStream())
           using (StreamWriter requestWriter = new StreamWriter(webStream, Encoding.ASCII))
           {
               requestWriter.Write(DATA);
           }

           try
           {
               WebResponse webResponse = request.GetResponse();
               using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
               using (StreamReader responseReader = new StreamReader(webStream))
               {
                   string response = responseReader.ReadToEnd();
                   Console.Out.WriteLine(response);
               }
           }
Posted
Updated 30-Dec-20 3:19am
Comments
Richard MacCutchan 21-Dec-20 4:25am
   
You need to check the logs from the server.
Vikram Singh Rathaur 21-Dec-20 5:38am
   
How?I don't know
Richard MacCutchan 21-Dec-20 5:47am
   
I have no knowledge of the server you are trying to connect with, so neither do I.
Gerry Schmitz 21-Dec-20 12:47pm
   
The server can't handle your request and it doesn't have a "unique" error response.

You need to verify yourself that your request is "valid" (format, content, etc.)

1 solution

Without knowing anything about the server receiving the request, what the endpoint expects in terms of data or authentication, this is pretty much a shot in the dark.
But according to the Microsoft Docs you might try replacing the following line of code
C#
using (Stream webStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, Encoding.ASCII))
       {
            requestWriter.Write(DATA);
       }


With this
C#
byte[] byteArray = Encoding.UTF8.GetBytes(DATA);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
   
Comments
Vikram Singh Rathaur 8-Jan-21 0:00am
   
Thanks. my problem resolved

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900