.net 如何强制 WebRequest 在 POST 期间发送 Authorization 标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21158298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:36:45  来源:igfitidea点击:

How to force WebRequest to send Authorization header during POST

.nethttptwitterwebrequest

提问by chris

When using WebRequest to send a POST, the Authorization header is not sent with the request even though I have manually set the header and set PreAuthenticate to true, eg:

使用 WebRequest 发送 POST 时,即使我手动设置了标头并将 PreAuthenticate 设置为 true,授权标头也不会随请求一起发送,例如:

webRequest.Headers["Authorization"] = "OAuth oauth_consumer_key=bFPD...";
webRequest.PreAuthenticate = true;

Using Fiddler I can see that the Authorization header is not sent. The target site (Twitter) returns a 400 (Bad request) rather than a 401 (Not authorized) which is therefore the incorrect challenge required for WebRequest to send the Authorization data. For information, the returned content is:

使用 Fiddler,我可以看到 Authorization 标头未发送。目标站点 (Twitter) 返回 400(错误请求)而不是 401(未授权),因此这是 WebRequest 发送授权数据所需的错误质询。返回的内容为:

{"errors":[{"message":"Bad Authentication data","code":215}]}

So, how do I get around this? How can I force WebRequest to send the Authorization with initial request? Note that the authorization data is not Basic Authentication, rather it is an OAuth string.

那么,我该如何解决这个问题?如何强制 WebRequest 发送带有初始请求的授权?请注意,授权数据不是基本身份验证,而是 OAuth 字符串。

Thanks

谢谢

回答by JuanPablo

Here's my solution. The value is in variable json.

这是我的解决方案。该值在变量 json 中。

var myUri = new Uri(fullpath);
var myWebRequest = WebRequest.Create(myUri);
var myHttpWebRequest = (HttpWebRequest)myWebRequest;
myHttpWebRequest.PreAuthenticate = true;
myHttpWebRequest.Headers.Add("Authorization", "Bearer " + AccessToken);
myHttpWebRequest.Accept = "application/json";

var myWebResponse = myWebRequest.GetResponse();
var responseStream = myWebResponse.GetResponseStream();
if (responseStream == null) return null;

var myStreamReader = new StreamReader(responseStream, Encoding.Default);
var json = myStreamReader.ReadToEnd();

responseStream.Close();
myWebResponse.Close();

回答by stevefinn

This drove me bonkers, but eventually found the answer in Adding Headers and Post data in RESTfull/HTTP Request in C#.

这让我很抓狂,但最终在 Add Headers and Post data in RESTfull/HTTP Request in C# 中找到了答案。

The solution for me was adding the Authorization Header BEFORE writing the request stream.

我的解决方案是在写入请求流之前添加授权标头。

Hope this helps.

希望这可以帮助。

回答by You

Try this, but there should be no space between the authorization headers.

试试这个,但授权标头之间不应该有空格。

var authHeader = "OAuth  oauth_consumer_key=bFPD...";
webRequest.Headers.Add("Authorization", authHeader);