Call works in Postman but not in C#

后端 未结 3 929
温柔的废话
温柔的废话 2021-01-26 13:02

I am trying to make a call to below URL and it works just fine in Browser (Chrome) and also in Postman, but for some reason, it doesn\'t work in C#.

Working in b

相关标签:
3条回答
  • 2021-01-26 13:04

    Thanks to Joshua & Vhoang!

    It's working after I changed code to below:

    var client = new RestClient("http://presta.craftingcrow.com/api/categories"); 
    var request = new RestRequest(Method.GET);
    request.AddHeader("cache-control", "no-cache");
    request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("AJWKBLWT47VR26QWPNFCPJLXC6217F6F:"));
    IRestResponse response = client.Execute(request);
    

    There was no need to add user-agent or include key in the hostname (URL)

    0 讨论(0)
  • 2021-01-26 13:06

    RestClient constructor accepts URI that doesn't include userinfo

              userinfo       host      port
              ┌──┴───┐ ┌──────┴──────┐ ┌┴┐
      https://john.doe@www.example.com:123/forum/questions/?tag=networking&order=newest#top
      └─┬─┘   └───────────┬──────────────┘└───────┬───────┘ └───────────┬─────────────┘ └┬┘
      scheme          authority                  path                 query           fragment
    

    See: https://en.wikipedia.org/wiki/Uniform_Resource_Identifier

    In order to make it work with RestSharp, we'll need to do a little bit of extra work here:

    // Old:
    // var client = new RestClient("http://AJWKBLWT47VR26QWPNFCPJLXC6217F6F@presta.craftingcrow.com/api/categories"); 
    
    // New:
    var client = new RestClient("http://presta.craftingcrow.com/api/categories")
    {
        Authenticator = new HttpBasicAuthenticator("AJWKBLWT47VR26QWPNFCPJLXC6217F6F", "")
    };
    
    0 讨论(0)
  • 2021-01-26 13:26

    Go into postman and, after you submit the request, check the Headers tab for anything that may have been added in the "temporary headers" section if you haven't specified anything in the Authorization tab.

    In this example, I haven't called out an Authorization header but Postman is supplying one anyway:

    Then add the missing relevant header(s) into your code. I like to click the "Code" button to the far right of the request. It gives you a dropdown so that you can choose pre-generated code in your desired language. This will most likely give you a reproducible example.

    0 讨论(0)
提交回复
热议问题