【发布时间】:2016-07-31 06:47:41
【问题描述】:
我们正在开发 Windows 窗体应用程序以向 Azure AD 验证 Windows 窗体应用程序。
我有几个问题,网上的资源似乎都过时了。
按照以下链接的建议,我创建了一个 webapi 和本机客户端 api 和 windows 窗体应用程序。
在 web api 中,我更新了清单文件如下
“oauth2Permissions”:[
{
"adminConsentDescription": "Allow the application to access ftpwebapi on behalf of the signed-in user.",
"adminConsentDisplayName": "Access ftpwebapi",
"id": "4eebeb18-aee6-408a-bea1-c090766dce23",
"isEnabled": true,
"origin": "Application",
"type": "User",
"userConsentDescription": "Allow the application to access ftpwebapi on your behalf.",
"userConsentDisplayName": "Access ftpwebapi",
"value": "user_impersonation"
}
],
并在keys下添加了我已经添加了2年的条目并将webapi添加到本机客户端应用程序中。
在 windows 窗体中,我在按钮单击事件中添加了以下代码。
private async void button1_Click(object sender, EventArgs e)
{
string authority = "https://login.windows.net/****";
string resourceURI = "https://***.com/WebApplication3";
string clientID = "********-5815-4358-****-*********";
Uri returnURI = new Uri("http://********.com");
AuthenticationContext authContext =
new AuthenticationContext(authority);
AuthenticationResult authResult =
authContext.AcquireToken(resourceURI, clientID, returnURI);
string authHeader = authResult.CreateAuthorizationHeader();
// don't do this in prod
System.Net.ServicePointManager.ServerCertificateValidationCallback =
((s, c, c2, se) => true);
HttpClient client = new HttpClient();
HttpRequestMessage request =
new HttpRequestMessage(HttpMethod.Get, "https://localhost:***/task/api/");
request.Headers.TryAddWithoutValidation("Authorization", authHeader);
var response = await client.SendAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
MessageBox.Show(responseString);
}
到目前为止是正确的方式吗?
我正在处理一个错误
var response = await client.SendAsync(request);
在 mscorlib.dll 中发生了“System.Net.Http.HttpRequestException”类型的异常,但未在用户代码中处理
附加信息:发送请求时出错。
【问题讨论】:
-
将 try/catch 添加到 sendAsync 并将您的异常内容发送给我:try { var response = await client.SendAsync(request); } catch (HttpRequestException e) { Console.WriteLine(e.InnerException.Message); }
标签: c# azure httpclient