HTTP Request works in Postman, but not in C# code

12,235

Solution 1

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.

Solution 2

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 enter image description here 3-A pop-up window will open, then choose whatever language you want, in your case it's C# enter image description here

Solution 3

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;

Solution 4

My suggestion would be retrieving raw request strings from postman and C# application and using something like https://text-compare.com/ to look for differences. The guess is there's some extremely minor difference like extra slash that is very difficult to notice with plain eye.

Share:
12,235

Related videos on Youtube

modugnico
Author by

modugnico

Updated on June 04, 2022

Comments

  • modugnico
    modugnico almost 2 years

    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.

    C# Code (Using https://flurl.dev):

    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
            };
        }
    }
    

    C# Request And Response:

    CSharp Request in Fiddler CSharp Response

    Postman Request And Response:

    Postman Headers Postman Response Postman Response in Fiddler

    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.

    • Tobias Tengler
      Tobias Tengler almost 5 years
      Have you tried using C#'s HttpClient? Does it produce the same result?
    • John Wu
      John Wu almost 5 years
      Is there a chance the 403 is coming from a proxy server?
    • modugnico
      modugnico almost 5 years
      @TobiasTengler Yes, i tried using HttpClient and it produces same result.
    • modugnico
      modugnico almost 5 years
      @JohnWu When I'm running the request with Fiddler, both Postman and C# returns 403. But without Fiddler Postman works but C# doesn't
  • modugnico
    modugnico almost 5 years
    i replaced the actual url with "example.com" because i don't want to show the real api here
  • modugnico
    modugnico almost 5 years
    I compared the request strings using the site you provided, but the result says: "The two texts are identical"
  • Duck Ling
    Duck Ling over 4 years
    Okay, so your code works. Now Go to Postman "Authorization" tab from the working example and check if the token you're using is the same as the one you have in your VS code
  • user1294510
    user1294510 almost 3 years
    omg this worked for me thanks!! but why does changing it to this specific protocol works?