使用httpclient(控制台程序)调用web api时,我遇到了一个问题
Program.cs的
static void Main(string[] args)
{
var token = GlobalVariables.GetAccessToken();
Console.WriteLine("================================");
Console.WriteLine("TOKEN");
Console.WriteLine($"Token : {token.Token}");
Console.WriteLine($"Expires : {token.ExpiresIn}");
Console.WriteLine("================================");
Console.WriteLine("1");
Console.WriteLine("================================");
CallApiEndpoint(ApiUrl, token.Token);
Console.WriteLine("================================");
Console.WriteLine("2");
Console.WriteLine("================================");
CallApiEndpoint(ApiUrl, token.Token);
Console.WriteLine("================================");
Console.WriteLine("3");
Console.WriteLine("================================");
CallApiEndpoint(ApiUrl, token.Token);
Console.WriteLine("================================");
Console.WriteLine("4");
Console.WriteLine("================================");
CallApiEndpoint(ApiUrl, token.Token);
Console.WriteLine("================================");
Console.WriteLine("5");
Console.WriteLine("================================");
CallApiEndpoint(ApiUrl, token.Token);
Console.WriteLine("================================");
Console.WriteLine("6");
Console.WriteLine("================================");
CallApiEndpoint(ApiUrl, token.Token);
Console.WriteLine("================================");
Console.Read();
}
static void CallApiEndpoint(string url, string token)
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(BaseUrl);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
var response = httpClient.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine(response.StatusCode);
}
}
}
Startup.cs
public void Configuration(IAppBuilder app)
{
UserManagerFactory = () => new UserManager<User>();
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
AllowInsecureHttp = true
};
app.UseOAuthBearerTokens(OAuthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
app.UseCookieAuthentication(new CookieAuthenticationOptions());
}
响应
提前致谢,
答案 0 :(得分:0)
经过数周的调查,我终于发现基础架构级401 unauthorized
Load Balancer
IIS
已归结为MachineKey
。
所以我只需将CLK
放在web.config
希望它有所帮助。