RestSharp C# HTTP POST Oauth 1

5

我在使用HTTP POST和Oauth 1、RestClient C#时遇到了困难。我能够成功地使用HTTP GET和Oauth进行调用,但是由于某些原因,HTTP Post失败了。我能够使用Postman并使用相同的凭据进行成功的HTTP POST调用,但是使用RestSharp失败了。也许有人可以帮助我找出问题所在。

以下是使用工作HTTP POST Oauth1 Postman调用的截图:

enter image description here

enter image description here

enter image description here

上面的Postman设置很好,这是我在C#和RestClient中所拥有的:

        public bool CreateShippingTemplate(string storeProviderStoreId, string consumerKey, string consumerSecret, string oAuthToken, string oAuthTokenSecret)
    {
        string url = "/shipping/templates";
        var request = GenerateSecureRequest(url, RequestType.POST, consumerKey, consumerSecret, oAuthToken, oAuthTokenSecret);

        var dataObj = new //ShippingTemplate
        {
            title = "Test Title 2",
            origin_country_id = "209",
            primary_cost = "1",
            secondary_cost = "1"
        };

        string dataObjJson = JsonConvert.SerializeObject(dataObj);

        request.AddParameter("application/json", dataObjJson, ParameterType.RequestBody);
        request.RequestFormat = DataFormat.Json;

        request.Method = Method.POST;
        request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
        var response = _restClient.ExecuteAsPost(request,"POST");

        return true;
    }



        private RestRequest GenerateSecureRequest(string url, RequestType requestType, string consumerKey, string consumerSecret, string oAuthToken, string oAuthTokenSecret)
    {
        OAuthBase oAuth = new OAuthBase();

        string nonce = oAuth.GenerateNonce();
        string timeStamp = oAuth.GenerateTimeStamp();
        string normalizedUrl;
        string normalizedRequestParameters;

        string relativeUri = url;
        string sig = oAuth.GenerateSignature(new Uri(BASE_URL.ToString() + relativeUri), consumerKey, consumerSecret, oAuthToken, oAuthTokenSecret, requestType.ToString(), timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters);

        var request = new RestRequest(relativeUri);
        request.Resource = string.Format(relativeUri);
        request.Method = Method.GET;
        request.AddParameter("oauth_consumer_key", consumerKey);
        request.AddParameter("oauth_token", oAuthToken);
        request.AddParameter("oauth_nonce", nonce);
        request.AddParameter("oauth_timestamp", timeStamp);
        request.AddParameter("oauth_signature_method", "HMAC-SHA1");
        request.AddParameter("oauth_version", "1.0");
        request.AddParameter("oauth_signature", sig);

        return request;
    }

我尝试使用RestClient和C#做了很多事情,但都没有成功。为了与工作中的Postman请求相匹配,我缺少什么?在RestSharp中,HTTP GET对我有效,只有HTTP Post无法正常工作。
谢谢。

1
我不知道“不工作”是什么意思。你应该从你的词汇表中删除它。相反,准确地描述出问题的具体情况。你是否收到异常?服务器返回了什么错误消息?它为什么不能按照你的期望工作? - mason
请求失败,状态为“Forbidden”,内容显示“oauth_problem=signature_invalid...” - lucas
2个回答

3

好的,我最终让我的工作起来了,之前我曾经试图自己实现签名创建,但走了同样错误的路线...因为我严重误解了PostMan RestSharp代码。 这其实可以更轻松地完成,因为RestSharp已经为你完成了所有操作!我希望这是PostMan给出的“代码”示例版本。无论如何,以下是在C#中适用于我的快速控制台应用程序的代码:

const string consumer_key = "abcd1234";
const string consumer_secret = "1234abcd";
const string access_token = "1a2b3c4d";
const string token_secret = "a12b3c4d";
const string URL = "https://aa.web.site.net/history/api/account/123456789/givemedata/search?offset=0&limit=50";

static void Main(string[] args)
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
var client = new RestClient(URL);
client.Authenticator = OAuth1Authenticator.ForAccessToken(consumer_key, consumer_secret, access_token, token_secret, RestSharp.Authenticators.OAuth.OAuthSignatureMethod.HmacSha1);
client.Timeout = -1;
var request = new RestRequest(URL, Method.POST);

request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\"start\": {\"from\": 1583074556000, \"to\": 1588258556000 } }", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Console.ReadKey();
}

是的,我知道,没有头信息、参数排序和哈希... 没有随机数 :)


2

谢谢 Pete,这段代码为我节省了数小时的尝试和错误!我添加的唯一代码是 Realm

OAuth1Authenticator lAuthenticator = OAuth1Authenticator.ForAccessToken(consumer_key, consumer_secret, access_token, token_secret, RestSharp.Authenticators.OAuth.OAuthSignatureMethod.HmacSha256);
lAuthenticator.Realm = "my_Realm";
client.Authenticator = lAuthenticator;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接