Windows.Web.Http.HttpClient + WEB API Windows身份验证

时间:2014-02-09 20:05:16

标签: asp.net-web-api windows-store-apps windows-8.1 winrt-httpclient

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

使用(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)))

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

2 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分: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);

但是,如果我需要传递登录信息和密码,我不知道企业身份验证功能的作用是什么......