使用RestSharp获取Magento 2.2.3管理员令牌遇错误求助
Troubleshooting Bad Request/NotFound When Fetching Magento 2.2.3 Admin Token with RestSharp
Hey there! Let's work through why you're hitting that frustrating error when trying to grab an admin token for Magento 2.2.3 using RestSharp. I'll break down the common issues in your code and setup, then share fixed code to get you back on track.
Key Issues in Your Current Code
Let's start with the obvious culprits:
- Typo in Content-Type Header: You wrote
aplication/jsoninstead ofapplication/json—this is a common reason for Bad Request errors, since Magento expects the correct JSON content type to process your request. - Manual JSON Serialization: RestSharp has a built-in method to handle JSON bodies more reliably than manual serialization +
AddParameter. - Lack of Debug Info: Your current code returns an empty string on failure, which gives you no clue what Magento is actually complaining about.
- Possible Endpoint Misalignment: Depending on your Magento setup, you might need to include
index.phpin the API endpoint path.
Fixed Code Examples
Updated magento.cs
using System; using RestSharp; using Newtonsoft.Json; namespace MagentoTest { public class magento { private RestClient Client { get; set; } private string Token { get; set; } public magento(string magentoUrl) { Client = new RestClient(magentoUrl); } public magento(string magentoUrl, string token) { Client = new RestClient(magentoUrl); Token = token; } public string GetAdminToken(string userName, string passWord) { // If your Magento uses index.php in URLs, update the endpoint to "/index.php/rest/V1/integration/admin/token" var request = CreateRequest("/rest/V1/integration/admin/token", Method.POST); var user = new Credentials { username = userName, password = passWord }; // Use RestSharp's built-in method to handle JSON body (auto-serializes + sets correct content type) request.AddJsonBody(user); var response = Client.Execute(request); // Add debug output to see exactly what's happening Console.WriteLine($"Status Code: {response.StatusCode}"); Console.WriteLine($"Magento Response: {response.Content}"); if (response.StatusCode == System.Net.HttpStatusCode.OK) { // Magento returns the token wrapped in quotes—trim them for clean usage return response.Content.Trim('"'); } else { // Return error details instead of empty string to help debug return $"Failed: {response.StatusCode} - {response.Content}"; } } private RestRequest CreateRequest(string endPoint, Method method) { var request = new RestRequest(endPoint, method); request.RequestFormat = DataFormat.Json; return request; } } }
Credentials.cs (no changes needed, included for completeness)
using System; namespace MagentoTest { public class Credentials { public string username { get; set; } public string password { get; set; } } }
Updated Program.cs (add output to see results)
using System; using MagentoTest; namespace Client { class Program { static void Main(string[] args) { // Replace with your actual admin credentials GetToken("your_admin_username", "your_admin_password"); Console.ReadLine(); // Keep console open to see output } static void GetToken(string userName, string passWord) { var m2 = new magento("http://beta.topprice24.com"); string token = m2.GetAdminToken(userName, passWord); Console.WriteLine($"Final Result: {token}"); } } }
Additional Checks to Ensure Success
- Validate Admin Credentials: Double-check that the username/password are valid Magento admin credentials with API access permissions.
- Magento API Configuration: Confirm the REST API is enabled in your Magento admin under Stores > Settings > Configuration > Services > Magento Web API > Web API Security.
- HTTPS vs HTTP: If your site uses HTTPS, switch your base URL to
https://—some Magento configurations block HTTP requests for admin API endpoints. - Endpoint Path: If you still get NotFound, try adding
index.phpto the endpoint (e.g.,/index.php/rest/V1/integration/admin/token).
Once you have a valid token, you can fetch category data by adding an authorization header to future RestSharp requests:
request.AddHeader("Authorization", $"Bearer {yourValidToken}");
内容的提问来源于stack exchange,提问作者pnut_rayhan93
相关产品推荐
相关产品推荐

