1.通过nuget添加restsharp类库;
官方调用例子:http://restsharp.org/
2.获取token
var httpClient = new HttpClient(); var discoveryClient = httpClient.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest { Address = IdentityServerBaseUrl, Policy = { RequireHttps = false } }).Result; // 请求令牌 var tokenResponse = httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = discoveryClient.TokenEndpoint, ClientId = ClientId, ClientSecret = ClientSecret, Scope = AllowScope }); return tokenResponse.Result.AccessToken;
注意:在core 项目里面,IdentityServerBaseUrl,ClientId,ClientSecret等在Appsetting.json文件里面
3.通过restsharp请求
var client = new RestClient(url);
client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", token)); var request = new RestRequest("", Method.GET); var response = client.Execute(request);
//response.ResponseStatus==ResponseStatus.Completed;请求成成功 //response.StatusCode=OK==HttpStatusCode.OK
var content=response.Content;//返回结果