问题
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 browser:
http://AJWKBLWT47VR26QWPNFCPJLXC6217F6F@presta.craftingcrow.com/api/categories
Working in Postman:
http://AJWKBLWT47VR26QWPNFCPJLXC6217F6F@presta.craftingcrow.com/api/categories
Not working in C# (RestSharp):
var client = new RestClient("http://AJWKBLWT47VR26QWPNFCPJLXC6217F6F@presta.craftingcrow.com/api/categories");
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("User-Agent", @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
IRestResponse response = client.Execute(request);
Response:
401 Unauthorized
P.S. If I remove User-Agent it still doesn't work. Why am I doing wrong here?
回答1:
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.
回答2:
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", "")
};
回答3:
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)
来源:https://stackoverflow.com/questions/59312022/call-works-in-postman-but-not-in-c-sharp