繁体   English   中英

C#如何在Http请求中添加参数?

[英]C# How can I add a parameter to my Http request?

我正在尝试为使用OAuth 2.0的控制台应用程序创建一个Logout功能。 但是,当我调用我的函数时,响应是:

{
  "error" : "invalid_token"
}

根据这些信息 ,这就是我如何制作Http请求:

var values = new Dictionary<string, string> { { "token", token.Token } };
var content = new FormUrlEncodedContent(values);

HttpClient client = new HttpClient();
var response = 
    await client.PostAsync("https://accounts.google.com/o/oauth2/revoke",content);

var responseString = await response.Content.ReadAsStringAsync();
Log.Info(responseString);

谷歌说:

要以编程方式撤消令牌,您的应用程序会向https://accounts.google.com/o/oauth2/revoke发出请求,并将令牌作为参数包含在内:

curl https://accounts.google.com/o/oauth2/revoke?token={token}

令牌可以是访问令牌或刷新令牌。 如果令牌是访问令牌并且它具有相应的刷新令牌,则刷新令牌也将被撤销。

如果成功处理了吊销,则响应的状态代码为200.对于错误条件,将返回状态代码400以及错误代码。

有人指出, PostAsync的第一个参数应该是https://accounts.google.com/o/oauth2/revoke?token= 但是,当我尝试时,我收到了以下回复:

{
  "error" : "invalid_request",
  "error_description" : "Missing required parameter: token"
}  

由于错误消息的不同,我觉得我在传递令牌时是"https://accounts.google.com/o/oauth2/revoke" ,或者我至少让参数部分失效,但我不是我确实是对的。

有没有明显的错误可能是问题的根源?

更新:

是否也可以在响应消息中看到状态代码?

是的,当我打印出response.StatusCode我看到返回是BadRequest意味着它在语法上与请求有关。

阅读RFC文档后

客户端通过在HTTP请求实体主体中使用"application/x-www-form-urlencoded"格式包含以下参数来构造请求:

....

例如,客户端可以使用以下请求请求撤销刷新令牌:

  POST /revoke HTTP/1.1 Host: server.example.com Content-Type: application/x-www-form-urlencoded Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW token=45ghiukldjahdnhzdauz&token_type_hint=refresh_token 

阅读本文后,他们建议使用POST,但没有说有必要,第二个参数token_type_hint是可选的。

但是, application/x-www-form-urlencoded部分是我不明白的。 有人可以清楚这是什么吗?

Google(Ruby)上的示例使用GET请求而不是POST。 我会尝试切换到HttpClient.GetAsync 大致:

HttpClient client = new HttpClient();
var response = 
    await client.GetAsync("https://accounts.google.com/o/oauth2/revoke?token=" + HttpServerUtility.UrlEncode(token.Token));

var responseString = await response.Content.ReadAsStringAsync();
Log.Info(responseString);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM