繁体   English   中英

使用RestSharp和OAuth2时如何解决UnsupportedMediatType

[英]How to solve UnsupportedMediatType when using RestSharp and OAuth2

几分钟前,我设法使我的代码与RestSharpOAuth2 ,检索了访问令牌。 现在,我想在对REST API进行的每次调用中都使用该令牌。 不幸的是,尽管响应状态已完成,但我仍然收到UnsupportedMediaType StatusCode

这是我发出该请求时的代码:

RestClient client = new RestClient("http://www.example.com/myapi/products/get");
client.Proxy = proxy;

RestRequest request = new RestRequest( ) { Method = Method.POST };
request.AddParameter("application/json", String.Format( "{{\"email\": \"{0}\", \"key\": \"{1}\"}}", email, key ), ParameterType.RequestBody);

request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");     

request.AddParameter("access_token",APIAuthenticator.Instance().GetAccessToken(proxy));

var response = client.Execute(request);

APIAuthenticator.Instance().GetAccessToken(proxy)可以正常工作,并且只需获取访问令牌即可。 那么问题是什么呢?

看看你在这里做什么

request.AddParameter("application/json", 
    String.Format( "{{\"email\": \"{0}\", \"key\": \"{1}\"}}", email, key ), 
    ParameterType.RequestBody);

request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); 
request.AddParameter("access_token",APIAuthenticator.Instance().GetAccessToken(proxy));

首先,使用application/json Content-Type将正文设置为JSON。 一个请求只能有一个主体。 最后两行所做的工作将覆盖原始行。 您将Content-Type设置为application/x-www-form-urlencoded并将正文设置为访问令牌。

您得到415不支持的媒体类型的原因很可能是因为资源端点期望数据(您的JSON)为application/json 它不支持您覆盖的类型。 如果发生这种情况,则您仍在发送错误的数据(您的访问令牌)。

那么如何发送访问令牌? 可能可以在查询字符串中发送它(取决于身份验证服务器的配置),即

.../myapi/products/get?access_token=yourAccessToken

但这更多用于隐式授予类型

更常见的方法是在Authorization标头中发送令牌,如RFC所示 ,例如

request.AddHeader("Authorization", "Bearer " + accessToken);

现在,这取决于在auth服务器中配置的配置文件,但是在大多数情况下,应该接受Bearer。

然后摆脱

//request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
//request.AddParameter("access_token",APIAuthenticator.Instance().GetAccessToken(proxy));

暂无
暂无

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

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