use*_*904 15 c# rest restful-authentication oauth oauth-2.0
我目前的工作是使用OAuth2来使用RESTful API.目前我研究了如何获取访问令牌,并且在我使用chrome扩展Rest Console时工作正常,但是当我尝试从我的应用程序执行此操作时,我总是收到错误,即我发送了无效的OAuth请求.您可以在下面看到我尝试使用API的三种方法,但没有成功.页面总是返回错误500.如果我错过了一些关键的东西,任何帮助将不胜感激.
var auth = "Bearer " + item.access_token;
/* First Attempt */
var client = new RestClient("http://<link>");
var request = new RestRequest("sample", Method.GET);
request.AddHeader("Authorization", auth);
request.AddHeader("Content-Type", "application/json;charset=UTF-8");
request.AddHeader("Pragma", "no-cache");
request.AddHeader("User-Agent", "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
var content = response.Content;
/* Second Attempt */
string sURL = "http://<link>/sample";
string result = "";
using (WebClient client = new WebClient())
{
client.Headers["Authorization"] = auth;
client.Headers["Content-Type"] = "application/json;charset=UTF-8";
client.Headers["Pragma"] = "no-cache";
client.Headers["User-Agent"] = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
client.Headers["Accept"] = "application/json";
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
var result1 = client.DownloadString(sURL);
}
/* Third Attempt */
var request = (HttpWebRequest)WebRequest.Create(sURL);
request.Method = "GET";
request.ContentType = "application/json;charset=UTF-8";
request.Accept = "application/json";
request.Headers["Authorization"] = auth;
request.UserAgent = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
string content;
HttpStatusCode statusCode;
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
var contentType = response.ContentType;
Encoding encoding = null;
if (contentType != null)
{
var match = Regex.Match(contentType, @"(?<=charset\=).*");
if (match.Success)
encoding = Encoding.GetEncoding(match.ToString());
}
encoding = encoding ?? Encoding.UTF8;
statusCode = ((HttpWebResponse)response).StatusCode;
using (var reader = new StreamReader(stream, encoding))
content = reader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)
- - - - 编辑 - - - -
对于第一次尝试,我还尝试将身份验证添加到客户端变量client.Authenticator = Authenticate;
whereOAuth2AuthorizationRequestHeaderAuthenticator Authenticate = new OAuth2AuthorizationRequestHeaderAuthenticator(item.access_token, item.token_type);
代码看起来是正确的。您所做的失败尝试表明问题在于令牌而不是代码。不记名令牌有过期时间。因此,就像您的令牌在您第一次使用 chrome REST 控制台扩展获取它和您编写代码之间一样过期了。但这里奇怪的情况是你得到的 500 错误代码。401 是令牌过期或不存在时的标准响应。500 错误代码始终意味着服务器错误。
归档时间: |
|
查看次数: |
1297 次 |
最近记录: |