c# - 如何使用 RestSharp 发送请求

标签 c# windows-phone-7 restsharp

我正在尝试使用 RestSharp 客户端发送请求,如下所示 我将授权码传递给以下函数

public void ExchangeCodeForToken(string code)
{
    if (string.IsNullOrEmpty(code))
    {
        OnAuthenticationFailed();
    }
    else
    {           
        var request = new RestRequest(this.TokenEndPoint, Method.POST);
        request.AddParameter("code", code);
        request.AddParameter("client_id", this.ClientId);
        request.AddParameter("client_secret", this.Secret);
        request.AddParameter("redirect_uri", "urn:ietf:wg:oauth:2.0:oob");
        request.AddParameter("grant_type", "authorization_code");
        request.AddHeader("content-type", "application/x-www-form-urlencoded");

        client.ExecuteAsync<AuthResult>(request, GetAccessToken);
    }
}

void GetAccessToken(IRestResponse<AuthResult> response)
{
    if (response == null || response.StatusCode != HttpStatusCode.OK
                         || response.Data == null 
                         || string.IsNullOrEmpty(response.Data.access_token))
    {
        OnAuthenticationFailed();
    }
    else
    {
        Debug.Assert(response.Data != null);
        AuthResult = response.Data;
        OnAuthenticated();
    }
}

但我收到 response.StatusCode = Bad Request。任何人都可以帮助我如何使用 Restsharp 客户端发布请求。

最佳答案

我的 RestSharp POST 方法:

var client = new RestClient(ServiceUrl);

var request = new RestRequest("/resource/", Method.POST);

// Json to post.
string jsonToSend = JsonHelper.ToJson(json);

request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;

try
{
    client.ExecuteAsync(request, response =>
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            // OK
        }
        else
        {
            // NOK
        }
    });
}
catch (Exception error)
{
    // Log
}

关于c# - 如何使用 RestSharp 发送请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11400879/

相关文章:

c# - 使用 C# WebBrowser 插入 CSS

c# - 如何通过 .NET/C# 查找 CPU 核心数?

c# - Windows Phone 7 配置/应用程序设置?

c# - 如何将值返回到异步方法中?

c# - 如何为绑定(bind)到 List<T> 的 dataGridView 设置 columnNames?

c# - 无法同时保存修改后的实体和新实体

c# - JSON.net - 字段是字符串或 List<string>

windows-phone-7 - 是否可以为 Windows Phone 7 模拟器模拟第二根手指?

c# - RestSharp 获取请求的完整 URL

c# - 使用restsharp put方法更新AtTask中的项目参数