Mostra um código em C# com erro 500 - Internal Server Erro
2023, Dec 4th

How to Solve 500 – Internal Server Error in C# .NET Framework / .NET Core REST Requests – When Postman Works, But Your Code Falters

By eliasdc.dev

In general, a 500 – Internal Server Error isn’t a client-side problem. However, if your requests work on Postman or another API platform for developers, and you don’t have control over the server-side, you may need to adjust your app’s request to make it work as well.

Summary

1 – Without further ado, I will demonstrate what resolved a 500 – Internal Server Error that I was experiencing with .NET Framework.

2 – If this doesn’t work for you, I will demonstrate how to identify possible problems for your case.

Let’s Go

Below is what solved a problem I encountered with .NET Framework (note: this issue didn’t occur with .NET Core)

Try setting this before making the request:

C#
httpClient.DefaultRequestHeaders.ExpectContinue = false


Code Example

C#
using (HttpClient httpClient = new HttpClient())
{              

    httpClient.BaseAddress = new Uri("...");

    httpClient.DefaultRequestHeaders.Accept
        .Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, httpClient.BaseAddress);
    request.Content = 
        new StringContent(JsonConvert.SerializeObject(objLogin), Encoding.UTF8, "application/json");
		
		//This ensures that the 'Expect' header isn't sent.
    httpClient.DefaultRequestHeaders.ExpectContinue = false;
	
    HttpResponseMessage response = httpClient.SendAsync(request).Result;

    Console.WriteLine(response.StatusCode + Environment.NewLine + response.ToString());

    Console.ReadKey();
}


Another test that worked for me was to set:

C#
request.Version = HttpVersion.Version10;

(I don’t recommend this code, but that’s not the focus of this post. Here’s an interesting discussion on the difference between HTTP versions 1.0 and 1.1: https://stackoverflow.com/questions/246859/http-1-0-vs-1-1#:~:text=HTTP%201.1%20comes%20with%20persistent,this%20is%20similar%20to%20pragm)


Code Example

C#
using (HttpClient httpClient = new HttpClient())
{              

    httpClient.BaseAddress = new Uri("...");

    httpClient.DefaultRequestHeaders.Accept
        .Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));


    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, httpClient.BaseAddress);
    request.Content = 
        new StringContent(JsonConvert.SerializeObject(objLogin), Encoding.UTF8, "application/json");
    
    //When you set the version to 1.0, headers and other request parameters change.
    request.Version = HttpVersion.Version10;
    
    HttpResponseMessage response = httpClient.SendAsync(request).Result;

    Console.WriteLine(response.StatusCode + Environment.NewLine + response.ToString());
    
    Console.ReadKey();
}


Didn’t work for you? Keep calm; now, I’ll provide you with more information on how to find a solution for your case.

If a request doesn’t work in your C# .NET Framework/Core application but works in another API platform like Postman on the same machine within the same computer network, it indicates that the two requests are different.

To discover the difference, first, try to identify all headers sent by your app and those sent by your API platform. For illustration, I will use Postman (https://www.postman.com/), but other platforms are similar.


How to see the headers in Postman?

In Postman, you can find it in the Headers tab or in the Console form (I prefer it in this case)

Headers Tab:


Console form:



Now, how to see headers in you app?

To make the programmer’s life easier (or not… lol), depending on the class used to make the request, some headers are added automatically. This made it difficult to discover the actual headers being sent in the request. To address this issue, I decided to create an API that receives a request and simply returns a List with the headers it received. To help you, I’ve uploaded this API on GitHub. Below are more details on how to use it:

GitHub Repository Address: https://github.com/eliasedc/ApiGetHeaders

FYI, the API was developed in .NET 6, but there are also two console projects simulating clients—one in .NET Framework 4.8 and another one in .NET 6.


The solution is configured to start the three projects in the same time. I did this to demonstrate that the same request to bring different results between the .NET Framework and .NET Core clients (the Swagger works too):


Both clients send the request in the same way (using the exact same code):

C#
using (HttpClient httpClient = new HttpClient())
{
    httpClient.BaseAddress = new Uri(pRequestUrl);
    httpClient.DefaultRequestHeaders.Accept
        .Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, httpClient.BaseAddress);
    request.Content =
        new StringContent(JsonSerializer.Serialize(pObjToSend), Encoding.UTF8, "application/json");

    HttpResponseMessage response = httpClient.SendAsync(request).Result;
    string strResult = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();

    Console.WriteLine(string.Join(Environment.NewLine, JsonSerializer.Deserialize<List<string>>(strResult)));

    Console.ReadKey();
}


See different results:

.NET Core


.NET Framework


Swagger


Postman

If you don’t want to use the clients in your case, you can run the API and input the endpoint of your application to call this API.


And now, what I do with this information?


Well, now you can compare the differences between your app’s headers and Postman’s headers. With this information, you can either insert, delete, or modify your app’s headers to match those in Postman. Alternatively, you can adjust the headers in Postman to match your app for testing purposes.

In my case, this revealed that the ‘500 – Internal Server Error’ was caused by the ‘Expect’ header within my application.


It don’t work to me, o what more I can see?

You can check the TLS protocol in your API platform and force your application to use the same.
FYI, by default, depending on your OS and which .NET version you are using, your system will try to find the best one.

In Postman you can see it in the Console form:


To change the protocol used in your application, simply include the following code before sending your request

C#
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;


Code Example:

C#
 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;
 
 using (HttpClient httpClient = new HttpClient())
 {
     ...
 }


That’s it

In this post, we will explore how to identify the causes of a 500 – Internal Server Error, possible solutions, and introduce a GitHub API to check and compare headers in your app.

I hope that it will help you.

See you next time!