使用 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));

首先,您将 body 设置为您的 JSON 和 application/json Content-Type。一个请求只能有一个body。您对最后两行所做的是覆盖原始内容。您将 Content-Type 设置为 application/x-www-form-urlencoded 并将 body 设置为访问令牌。

您收到 415 不受支持的媒体类型的最可能原因是资源端点期望数据(您的 JSON)为 application/json。它不支持您覆盖它的类型。如果确实如此,您仍然发送了错误的数据(您的访问令牌)。

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

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

但这更多地与 Implicit Grant Type 一起使用。

更常见的方式是在 Authorization header 中发送令牌,如 here in the 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));