如何通过c#中的oauth 2.0从ebay获取访问令牌

Mic*_*les 6 c# rest oauth token

这不是一个问题,而是一个答案.我想我想与你分享这个,因为我对ebay OAuth 2.0与ac #web应用程序的结合有点困惑.

我尝试开始使用RESTsharp库,但却陷入了创建正文内容的地步.RESTsharp更喜欢XML或JSON,ebay想要一个带params的字符串.

所以,如果你遇到同样的问题,给你一点帮助,我决定发布我的解决方案(不使用RESTsharp).

public class HomeController : Controller {
    string clientId = "YOUR_CLIENT_ID";
    string clientSecret = "YOUR_CLIENT_SECRET";
    string ruName = "YOUR_RU_NAME";
Run Code Online (Sandbox Code Playgroud)

//重定向请求以获取请求令牌

    public ActionResult Index() {
        var authorizationUrl =
            "https://signin.sandbox.ebay.de/authorize?" +
            "client_id=" + clientId + "&" +
            "redirect_uri=" + ruName + "&" +
            "response_type=code";

        Response.Redirect(authorizationUrl);
        return View();
    }
Run Code Online (Sandbox Code Playgroud)

//我使用Test作为在控制器中测试结果的方法,在这里使用适当的方法

    public ActionResult Test(string code)
    {
        ViewBag.Code = code;

        // Base 64 encode client Id and client secret
        var clientString = clientId + ":" + clientSecret;
        byte[] clientEncode = Encoding.UTF8.GetBytes(clientString);
        var credentials = "Basic " + System.Convert.ToBase64String(clientEncode);

        HttpWebRequest request = WebRequest.Create("https://api.sandbox.ebay.com/identity/v1/oauth2/token")
            as HttpWebRequest;

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";

        request.Headers.Add(HttpRequestHeader.Authorization, credentials);

        var codeEncoded = HttpUtility.UrlEncode(code);

        var body = "grant_type=authorization_code&code=" + codeEncoded + "&redirect_uri=" + ruName;

        // Encode the parameters as form data
        byte[] formData = UTF8Encoding.UTF8.GetBytes(body);
        request.ContentLength = formData.Length;

        // Send the request
        using (Stream post = request.GetRequestStream())
        {
            post.Write(formData, 0, formData.Length);
        }

        // Pick up the response
        string result = null;
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            result = reader.ReadToEnd();
        }

        ViewBag.Response = result;

        return View();
    }
Run Code Online (Sandbox Code Playgroud)

如果输出ViewBag.Response,您将看到授权码.玩得开心.

use*_*319 0

您的重定向网址在沙箱中看起来如何?看起来 url 应该是 https。在此阶段,在开发环境中,没有带有 https 的服务器。你是怎么处理的?