3

我使用 Windows.Web.Http.HttpClient 连接到我的 WEB API。应用程序没有提示输入用户名和密码,但最近我通过将 AuthorizeAttribute 过滤器从 Action 移动到 Class 级别来更改 WEB API。现在我的 Windows 商店 8.1 应用程序提示输入用户 ID 和密码。请告诉我如何设置 HttpClient 不提示登录名和密码。任何人都可以建议我是否需要将标头添加到我的 httpcleint

using (Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient()) { // 添加用户代理头 var headers = httpClient.DefaultRequestHeaders;

// 从用户那里检查标头值的安全方法是 TryParseAdd 方法 // 因为我们知道这个标头是可以的,所以我们使用 ParseAdd 会抛出异常 // 带有错误值 - http://msdn.microsoft。 com/en-us/library/windows/apps/dn440594.aspx

                headers.UserAgent.ParseAdd("ie");
                headers.UserAgent.ParseAdd("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");


                using (var response = await httpClient.GetAsync(new Uri(url)))

我看不到发送默认凭据的方法。

4

2 回答 2

12

使用 禁用 UI 对话框HttpBaseProtocolFilter.AllowUI。试试这个:

Windows.Web.Http.Filters.HttpBaseProtocolFilter filter =
    new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.AllowUI = false;
HttpClient client = new HttpClient(filter);

Uri uri = new Uri("http://localhost/?basic=1");
var response = await client.GetAsync(uri);
System.Diagnostics.Debug.WriteLine(response);

你需要凭证吗?使用HttpBaseProtocolFilter.ServerCredential. 试试这个:

Uri uri = new Uri("http://localhost?ntlm=1");

Windows.Web.Http.Filters.HttpBaseProtocolFilter filter =
    new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.AllowUI = false;

// Set credentials that will be sent to the server.
filter.ServerCredential =
    new Windows.Security.Credentials.PasswordCredential(
        uri.ToString(),
        "userName",
        "abracadabra");

HttpClient client = new HttpClient(filter);
var response = await client.GetAsync(uri);
System.Diagnostics.Debug.WriteLine(response);

您需要默认的 Windows 凭据(域凭据)吗?只需将企业身份验证功能添加到您的Package.appxmanifest

于 2014-02-10T06:56:12.870 回答
0

我尝试应用您的解决方案,但它没有按预期工作,或者我不明白我应该做什么。我需要使用Windows 凭据,并且我已在我的 UWP 应用上启用了企业身份验证功能。

我使用您建议的代码:

var filter = new HttpBaseProtocolFilter();
filter.AllowUI = false;
var client = new HttpClient(filter);
HttpResponseMessage response = new HttpResponseMessage();
response = await client.PostAsync(concUri, null);

但是响应返回给我一个401.3 错误...

如果我将登录名/密码添加到ServerCredential,则效果很好:

var filter = new HttpBaseProtocolFilter();
filter.AllowUI = false;
filter.ServerCredential  = new Windows.Security.Credentials.PasswordCredential(WebServiceConstants.WebServiceUrl.ToString(), "login", "password");
var client = new HttpClient(filter);
HttpResponseMessage response = new HttpResponseMessage();
response = await client.GetAsync(concUri);

但是我看不到在这种情况下企业身份验证功能的作用是什么,如果我需要传递登录名和密码......

于 2016-10-25T14:24:09.780 回答