I want to do a simple HTTP request in C#, but something is not working and all I got is 403 Forbidden
status code.
When I try to do same request in Postman, everything works fine.
I tried to run Fiddler and see all headers that are being sent by Postman. I copy-pasted all of them, but i still got 403 Forbidden
in the request sent by C# code.
public static void Main(string[] args)
{
FlurlHttp.Configure(settings => {
settings.HttpClientFactory = new MyClientFactory();
});
var url = "https://example.com"
.AppendPathSegments(new[] { "v1", "oauth", "accesstoken" })
.SetQueryParam("grant_type", "client_credentials")
.AllowAnyHttpStatus()
.WithBasicAuth("username", "password")
.WithHeaders(new {
User_Agent = "Something/0.4.0 Dalvik/2.1.0 (Linux; U; Android 5.1.1; SM-G975F Build/NRD90M)",
X_Secret_Header = "secret_encoded_value",
accept_encoding = "gzip, deflate",
Accept = "*/*"
});
HttpResponseMessage msg = url.GetAsync().Result;
Console.WriteLine("StatusCodeString: " + msg.StatusCode.ToString());
Console.WriteLine();
Console.WriteLine(msg.Content.ReadAsStringAsync().Result);
}
class MyClientFactory : DefaultHttpClientFactory
{
public override HttpMessageHandler CreateMessageHandler()
{
return new HttpClientHandler
{
AllowAutoRedirect = false
};
}
}
Can someone explain me why is this not working? Same headers, same everything.
I replaced the url with "example.com" because i don't want to show the real API URL here.
Also sorry for so many images.. I don't know how to show the problem here in other way.
From Postman there should be a link on the right side called code. Click that and then select C# to get the code generated by Postman. Paste that in and try it out.
For me the problem was the TLS settings in C#. Try adding this line at the start of your app or just before your HTTP request code:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
I know this old, but to get the same C# code as postman sent, let the postman generate the code for, but first you must get RestSharp lib from nuget or from PM console type this:
Install-Package RestRequest -Version 1.2.0
Steps:
1- Call your rest api from postman
2- Press the code button 3-A pop-up window will open, then choose whatever language you want, in your case it's C#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With