我使用 Windows.Web.Http.HttpClient连接到我的WEB API.应用程序没有提示用户名和密码,但最近我通过将AuthorizeAttribute过滤器从Action级别移动到类级别来更改WEB API.现在我的Windows应用商店8.1应用程
使用(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)))
我没有看到发送默认凭据的方法.
使用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凭据(域凭据)吗?只需将Enterprise Authentication功能添加到Package.appxmanifest即可.