如何强制WebRequest在POST期间发送授权标头 [英] How to force WebRequest to send Authorization header during POST

查看:568
本文介绍了如何强制WebRequest在POST期间发送授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.Headers["Authorization"] = "OAuth oauth_consumer_key=bFPD...";
webRequest.PreAuthenticate = true;

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

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:

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

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

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.

谢谢

推荐答案

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

Here's my solution. The value is in variable 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();

这篇关于如何强制WebRequest在POST期间发送授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆