C#中如何在URL传递大括号?Facebook Graph API调用问题
Hey there! Let's work through how to correctly pass fields when calling the Facebook Graph API from C#—it's usually a matter of proper URL construction or avoiding common pitfalls. Here's what you need to know:
1. Correctly Structure Your API Request
The key is using the fields query parameter to specify exactly what data you want. For example, if you need a user's ID, name, email, and profile picture, your parameter would look like fields=id,name,email,picture.width(500).
Instead of manually concatenating the URL (which can lead to encoding errors), use UriBuilder and HttpUtility to safely build your request:
using System; using System.Net.Http; using System.Threading.Tasks; using System.Web; public async Task GetFacebookUserData() { // Replace these with your actual values string accessToken = "YOUR_VALID_ACCESS_TOKEN"; string targetId = "USER_OR_PAGE_ID"; string requestedFields = "id,name,email,picture.width(500)"; // Build the API URL safely var uriBuilder = new UriBuilder($"https://graph.facebook.com/v18.0/{targetId}"); var queryParams = HttpUtility.ParseQueryString(uriBuilder.Query); queryParams["access_token"] = accessToken; queryParams["fields"] = requestedFields; uriBuilder.Query = queryParams.ToString(); using (var httpClient = new HttpClient()) { try { HttpResponseMessage response = await httpClient.GetAsync(uriBuilder.Uri); response.EnsureSuccessStatusCode(); // Throws if HTTP status code is an error string responseJson = await response.Content.ReadAsStringAsync(); // Process the JSON (use System.Text.Json or Newtonsoft.Json to deserialize) Console.WriteLine(responseJson); } catch (HttpRequestException ex) { Console.WriteLine($"Request failed: {ex.Message}"); } } }
2. Avoid Common Pitfalls
- Missing API Version: Always specify the latest stable API version (like
v18.0) in your URL. Older versions may deprecate fields or change behavior. - Incorrect Field Names: Double-check the official Facebook Graph API documentation for valid field names—make sure you're using exact, supported names.
- Insufficient Permissions: Some fields (like
email) require specific user permissions. Verify your access token has the necessary scopes using the Graph API Explorer first. - URL Encoding Errors: Manual URL concatenation can break when fields contain special characters (like commas or parentheses). Using
UriBuilderhandles encoding automatically.
3. Test with Graph API Explorer First
Before writing C# code, test your field selection in the Graph API Explorer:
- Enter your access token and the target ID.
- Add the
fieldsparameter with your desired fields. - If the explorer returns the correct data, your C# request should mirror that exact parameter setup.
内容的提问来源于stack exchange,提问作者Uzair Jamal

