调用在 Postman 中有效,但在 C# 中无效

Call works in Postman but not in C#(调用在 Postman 中有效,但在 C# 中无效)
本文介绍了调用在 Postman 中有效,但在 C# 中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调用以下 URL,它在浏览器 (Chrome) 和 Postman 中都可以正常工作,但由于某种原因,它在 C# 中不起作用.

在浏览器中工作:

附:如果我删除 User-Agent 它仍然不起作用.为什么我在这里做错了?

解决方案

感谢 Joshua &旺旺!

我将代码更改为以下代码后它正在工作:

var client = new RestClient("http://presta.craftingcrow.com/api/categories");var request = new RestRequest(Method.GET);request.AddHeader("缓存控制", "无缓存");request.AddHeader("授权", "基本" + Convert.ToBase64String(Encoding.Default.GetBytes("AJWKBLWT47VR26QWPNFCPJLXC6217F6F:"));IRestResponse 响应 = client.Execute(request);

无需添加用户代理或在主机名 (URL) 中包含密钥

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?

解决方案

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)

这篇关于调用在 Postman 中有效,但在 C# 中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)