![](/img/trans.png)
[英]How to access Facebook profile information by using ASP.NET MVC 5
[英]How to access the users Email id with asp.net mvc facebook?
我使用此鏈接作為起點,因為我是Asp.net MVC的新手。
我已經能夠獲取facebook用戶的數據我應該使用哪些權限來獲取用戶的電子郵件ID以及在哪里?
dynamic me = client.Get("me");
if (response.ContainsKey("verified"))
{
facebookVerified = response["verified"];
}
else
{
facebookVerified = false;
}
db.ExternalUsers.Add(new ExternalUserInformation
{
UserId = newUser.UserId,
FullName = me.name,
Link = me.link,
Email = model.Email, // Want the Email ID from Facebook
Gender = me.gender,
Verified = facebookVerified
});
登錄代碼:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
你在這里缺少的是獲得從Facebook獲取電子郵件地址的額外許可。
請參閱以下兩個屏幕截圖,第二個屏幕截圖請求以獲取其他信
為此,您需要將此附加必需信息作為“范圍”。
我今天做了一個關於如何登錄facebook的小教程,可以在這里閱讀 - 使用Facebook登錄ASP.NET MVC 4 。 這將回答您的大部分查詢。
對於你的問題,你應該做的是:
創建一個FacebookScopedClient類(下面的代碼),然后在你的AuthConfig.cs中使用它
var facebooksocialData = new Dictionary<string, object>();
facebooksocialData.Add("scope", "email, publish_stream, read_stream");
OAuthWebSecurity.RegisterClient(new FacebookScopedClient(
appId: "xxxxxxxx",
appSecret: "xxxxxxxxxxxxxxxxxxx",
scope:"email, user_likes, friends_likes, user_birthday),
"Facebook",
null
);
FacebookScopedClient類的代碼 -
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using DotNetOpenAuth.AspNet;
using Newtonsoft.Json;
public class FacebookScopedClient : IAuthenticationClient
{
private string appId;
private string appSecret;
private string scope;
private const string baseUrl = "https://www.facebook.com/dialog/oauth?client_id=";
public const string graphApiToken = "https://graph.facebook.com/oauth/access_token?";
public const string graphApiMe = "https://graph.facebook.com/me?";
private static string GetHTML(string URL)
{
string connectionString = URL;
try
{
System.Net.HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(connectionString);
myRequest.Credentials = CredentialCache.DefaultCredentials;
//// Get the response
WebResponse webResponse = myRequest.GetResponse();
Stream respStream = webResponse.GetResponseStream();
////
StreamReader ioStream = new StreamReader(respStream);
string pageContent = ioStream.ReadToEnd();
//// Close streams
ioStream.Close();
respStream.Close();
return pageContent;
}
catch (Exception)
{
}
return null;
}
private IDictionary<string, string> GetUserData(string accessCode, string redirectURI)
{
string token = GetHTML(graphApiToken + "client_id=" + appId + "&redirect_uri=" + HttpUtility.UrlEncode(redirectURI) + "&client_secret=" + appSecret + "&code=" + accessCode);
if (token == null || token == "")
{
return null;
}
string access_token = token.Substring(token.IndexOf("access_token="), token.IndexOf("&"));
string data = GetHTML(graphApiMe + "fields=id,name,email,username,gender,link&" + access_token);
// this dictionary must contains
Dictionary<string, string> userData = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
return userData;
}
public FacebookScopedClient(string appId, string appSecret, string scope)
{
this.appId = appId;
this.appSecret = appSecret;
this.scope = scope;
}
public string ProviderName
{
get { return "Facebook"; }
}
public void RequestAuthentication(System.Web.HttpContextBase context, Uri returnUrl)
{
string url = baseUrl + appId + "&redirect_uri=" + HttpUtility.UrlEncode(returnUrl.ToString()) + "&scope=" + scope;
context.Response.Redirect(url);
}
public AuthenticationResult VerifyAuthentication(System.Web.HttpContextBase context)
{
string code = context.Request.QueryString["code"];
string rawUrl = context.Request.Url.OriginalString;
//From this we need to remove code portion
rawUrl = Regex.Replace(rawUrl, "&code=[^&]*", "");
IDictionary<string, string> userData = GetUserData(code, rawUrl);
if (userData == null)
return new AuthenticationResult(false, ProviderName, null, null, null);
string id = userData["id"];
string username = userData["username"];
userData.Remove("id");
userData.Remove("username");
AuthenticationResult result = new AuthenticationResult(true, ProviderName, id, username, userData);
return result;
}
}
參考文獻:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.