identityServer4+ RestSharp调用webapi
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文件里面
![](https://img2018.cnblogs.com/blog/1752854/201907/1752854-20190726135751766-464307811.png)
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;//返回结果