使用ASP.NET中的Live Connect API检索用户的电子邮件地址

时间:2012-03-19 08:04:50

标签: c# json asp.net-mvc-3 model-view-controller windows-live

所以我对ASP.NET MVC和Windows Live Connect API还不熟悉。基本上我正在尝试将Live登录整合到我的网站中。当用户登录时,Live会请求他们为我的应用程序提供某些信息的权限,将用户发送到我的应用程序设置中指定的重定向uri,并附加查询字符串。在这里,如果用户第一次登录该站点,我希望他们的基本信息存储在我的服务器上(名字,姓氏,电子邮件)。我已经能够获得他们的名字和姓氏,但我很难找到如何检索他们的主要电子邮件地址。我会解释到目前为止我做了什么。

我找不到将Live connect集成到MVC应用程序的最佳方法,所以我做了最好的猜测。我在我的重定向uri中指定了一个控制器动作,它使用查询字符串“code”来构造HTTP Post。

HttpRequest req = System.Web.HttpContext.Current.Request;

            string myAuthCode = req.QueryString["code"];
            string myAppId = ConfigurationManager.AppSettings.Get("wll_appid");
            string mySecret = ConfigurationManager.AppSettings.Get("wll_secret");
            string postData = "client_id=" + myAppId + "&redirect_uri=http%3A%2F%2Fmscontestplatformtest.com%2FContestPlatform%2FUser%2FSignIn&client_secret=" + mySecret + "&code=" + myAuthCode + "&grant_type=authorization_code";

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            WebRequest request = WebRequest.Create("https://oauth.live.com/token");
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            request.Method = "POST";

获取JSON格式的字符串响应并提取access_token。然后我使用此访问令牌构建HTTP GET调用,如下所示。

request = WebRequest.Create("https://apis.live.net/v5.0/me?access_token=" + r.access_token);
            response = request.GetResponse();
            reader = new StreamReader(response.GetResponseStream());

            string userInfo = reader.ReadToEnd(); 

上面的GET调用为我提供了这个JSON字符串:

{ 
    "id": "02b4b930697bbea1", 
    "name": "Daniel Hines", 
    "first_name": "Daniel", 
    "last_name": "Hines", 
    "link": "http://profile.live.com/cid-02b4b930697bbea1/", 
    "gender": "male", 
    "locale": "en_US", 
    "updated_time": "2011-10-14T21:40:38+0000" 
} 

这是所有公开信息并且很棒,除了主要的电子邮件地址之外,我几乎拥有所需的一切。我需要什么样的GET电话来检索电子邮件?

另外,我是这样做的吗?

1 个答案:

答案 0 :(得分:5)

好的我明白了!

我只需要将范围“wl.emails”添加到我的登录链接中。然后我的GET电话将返回他们的电子邮件地址。