【问题标题】:WebClient not sending Authorization Header to Web Service in Windows PhoneWebClient 未向 Windows Phone 中的 Web 服务发送授权标头
【发布时间】:2014-05-22 23:58:51
【问题描述】:

这是在 Windows Phone 上使用 WebClient 的情况。
我能够将数据拉取并推送到使用 asp.net Web Api 托管的 Web 服务。
现在,我在 Web 服务和 Windows Phone 代码上启用了基本身份验证,将标头添加到 WebClient。
我注意到授权标头没有到达 Web 服务,因此 Web 服务抛出了错误的请求。
已搜索 stackoverflow 和博客,但无法获取授权标头以使 Web 服务正常工作。
关于上述问题的一些方向将有很大帮助。

【问题讨论】:

标签: windows-phone-7 asp.net-web-api webclient restful-authentication


【解决方案1】:

由于某种原因,webclient 没有发送授权标头。

我从我的网络中询问了一位 windows phone 冠军。他建议安装 nuget 包 HttpClient。并使用 HttpClient 而不是 WebClient。这个 HttpClient 即使在 wp7 上也支持异步和等待。可以让它轻松工作。

nuget package for httpclient

示例代码:

string api = "/api/example/?id=abc";
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:0000/");

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue     
                                                  ("Basic", Convert.ToBase64String
                                                              (
                                                                  new Helpers().StringToAscii(Username, Password)      
                                                              )
                                                   );
var resultString = await client.GetStringAsync(api);

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 2016-06-27
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多