2017-06-20 77 views
1

有人可以幫我轉換這個ASP .Net核心示例(在我的Web Api中使用從Auth0使用管理API),它將RestSharp合併爲一個使用HttpClient的示例?將代碼從RestSharp轉換爲HttpClient

var client = new RestClient("https://YOUR_AUTH0_DOMAIN/oauth/token"); 
var request = new RestRequest(Method.POST); 
request.AddHeader("content-type", "application/json"); 
request.AddParameter("application/json", "{\"grant_type\":\"client_credentials\",\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"audience\": \"https://YOUR_AUTH0_DOMAIN/api/v2/\"}", ParameterType.RequestBody); 
IRestResponse response = client.Execute(request); 

我一直在掙扎......我有這樣的:

var client = new HttpClient(); 
client.DefaultRequestHeaders.Accept.Clear(); 
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
client.BaseAddress = new Uri("https://YOUR_AUTH0_DOMAIN/oauth/token"); 

,但我不知道休息...謝謝

回答

1

你需要採取請求正文並創建要發佈的內容

var client = new HttpClient(); 
client.DefaultRequestHeaders.Accept.Clear(); 
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
client.BaseAddress = new Uri("https://YOUR_AUTH0_DOMAIN/oauth/token"); 

var json = "{\"grant_type\":\"client_credentials\",\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"audience\": \"https://YOUR_AUTH0_DOMAIN/api/v2/\"}" 
var content = new StringContent(json, Encoding.UTF8, "application/json"); 

var response = await client.PostAsync("", content); 
+0

我相信你知道,但它可能值得一提的OP(因爲沒有結構的帖子,它很難給我llustrate)。爲每個請求創建一個'HttpClient'實例是一個壞主意,它最好在一個類中使用共享的'HttpClient'對象。 – maccettura

+0

@maccettura是的。我知道,值得一提的是。 – Nkosi