You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用RestSharp调用Magento2 REST API获取分类并使用Admin Token

How to Use Admin Token with RestSharp to Fetch Magento 2 Categories

Hey there! Let's get your category API call working properly. I see you've already nailed getting the admin token—great start! The main hurdles right now are sharing that token with your getCategories method and making sure your API request is correctly formatted for Magento 2.

Step 1: Share the Token Between Methods

Right now, your Main method and getCategories method don't communicate. The easiest way to pass the token is to modify getCategories to accept the token as a parameter, then call it directly from Main once you have the token.

Step 2: Fix the API Endpoint

Magento 2's category API needs a store code in the endpoint (just like your token request uses /rest/default/...). Your current endpoint /rest/V1/categories is missing this, which might cause permission or routing issues. Update it to /rest/default/V1/categories.

Step 3: Polish the Request Details

Make sure you include the Accept header to tell Magento you want JSON back, and double-check the Authorization header format (it should be Bearer [your-token]).

Updated Full Code

Here's your code with all these fixes applied:

using RestSharp;
using Newtonsoft.Json;

class Program
{
    static void Main(string[] args)
    {
        // Base URL for your Magento store
        string host = "http://beta.topprice24.com";
        // Endpoint to get admin token
        string tokenEndpoint = "/rest/default/V1/integration/admin/token";
        
        RestClient restClient = new RestClient(host);
        var tokenRequest = new RestRequest(tokenEndpoint, Method.Post);
        
        // Set up credentials
        var userCredentials = new Credentials 
        { 
            username = "blabla", 
            password = "blabla" 
        };
        string inputJson = JsonConvert.SerializeObject(userCredentials);
        
        // Add request headers
        tokenRequest.AddHeader("Content-Type", "application/json");
        tokenRequest.AddHeader("Accept", "application/json");
        
        // Add request body
        tokenRequest.AddParameter("application/json", inputJson, ParameterType.RequestBody);
        
        // Execute token request
        var tokenResponse = restClient.Execute(tokenRequest);
        string adminToken = tokenResponse.Content?.Trim('"'); // Remove quotes from the token string
        
        if (!string.IsNullOrEmpty(adminToken))
        {
            // Call getCategories with the token we just got
            GetCategories(host, adminToken);
        }
        else
        {
            Console.WriteLine("Failed to retrieve admin token.");
        }
    }

    static void GetCategories(string host, string adminToken)
    {
        // Updated endpoint with store code
        string categoryEndpoint = "/rest/default/V1/categories";
        RestClient restClient = new RestClient(host);
        var categoryRequest = new RestRequest(categoryEndpoint, Method.Get);
        
        // Add authorization header with Bearer token
        categoryRequest.AddHeader("Authorization", $"Bearer {adminToken}");
        // Tell Magento we accept JSON responses
        categoryRequest.AddHeader("Accept", "application/json");
        
        // Execute category request
        var categoryResponse = restClient.Execute(categoryRequest);
        string responseBody = categoryResponse.Content;
        
        // Do something with the category data (e.g., print it or parse it)
        Console.WriteLine("Category Response:");
        Console.WriteLine(responseBody);
    }
}

// Credentials class for serialization
public class Credentials
{
    public string username { get; set; }
    public string password { get; set; }
}

Key Changes Explained:

  • Token Passing: GetCategories now takes adminToken as a parameter, so we can pass the token directly from Main after retrieving it.
  • Token Cleaning: The token response comes wrapped in quotes, so we use Trim('"') to remove them—this ensures the Authorization header is formatted correctly.
  • Fixed Endpoint: Added /default/ to the category endpoint to match the token request's store code.
  • Static Method: Changed getCategories to static so it can be called directly from the static Main method (alternatively, you could create an instance of the class, but static is simpler here).
  • Error Check: Added a quick check to make sure we actually got a token before trying to fetch categories.

Once you run this, you should see the category data returned in the console. If you need to parse the JSON into C# objects, you can use JsonConvert.DeserializeObject<T> with a category model class (you can generate this from Magento's API response using a tool like JSON to C#).

内容的提问来源于stack exchange,提问作者pnut_rayhan93

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:58:12