使用MVC 3(查看已發佈的示例),我創建了一個視圖,其中登錄開始。控制器是:
public ActionResult Logon()
{
_fb = new FacebookClient();
var csrfToken = Guid.NewGuid().ToString();
Session["fb_csrf_token"] = csrfToken;
var state = Convert.ToBase64String(Encoding.UTF8.GetBytes(_fb.SerializeJson(new { returnUrl = returnUrl, csrf = csrfToken })));
var fbLoginUrl = _fb.GetLoginUrl(
new
{
client_id = AppId,
client_secret = Appsecret,
redirect_uri = RedirectUri,
response_type = "code",
scope = Scope,
state = state
});
return Redirect(fbLoginUrl.AbsoluteUri);
}
其中RETURNURL是在我的應用程序(/家/ fbhome)所連接的觀看區域和RedirectUri是將涉及第二步驟中的視圖(loginresult):
public ActionResult Loginresult(string code, string state)
{
if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(state))
return RedirectToAction("Index", "Home");
// first validate the csrf token
_fb = new FacebookClient();
dynamic decodedState;
try
{
decodedState = _fb.DeserializeJson(Encoding.UTF8.GetString(Convert.FromBase64String(state)), null);
var exepectedCsrfToken = Session["fb_csrf_token"] as string;
// make the fb_csrf_token invalid
Session["fb_csrf_token"] = null;
if (!(decodedState is IDictionary<string, object>) || !decodedState.ContainsKey("csrf") || string.IsNullOrWhiteSpace(exepectedCsrfToken) || exepectedCsrfToken != decodedState.csrf)
{
return RedirectToAction("Index", "Home");
}
}
catch
{
// log exception
return RedirectToAction("Index", "Home");
}
try
{
dynamic result = _fb.Post("oauth/access_token",
new
{
client_id = AppId,
client_secret = Appsecret,
redirect_uri = RedirectUri,
code = code
});
Session["fb_access_token"] = result.access_token;
if (result.ContainsKey("expires"))
Session["fb_expires_in"] = DateTime.Now.AddSeconds(result.expires);
if (decodedState.ContainsKey("returnUrl"))
{
if (Url.IsLocalUrl(decodedState.returnUrl))
return Redirect(decodedState.returnUrl);
return Redirect(decodedState.returnUrl + "/notlocal");
}
return RedirectToAction("Index", "Home");
}
catch
{
// log exception
return RedirectToAction("Index", "Home");
}
}
所以,據我瞭解,用戶進入網站(/ home/index),然後點擊鏈接(/ home/loggon),facebook答案(/ home/loginresult),用戶被重定向到/ home/fbhome
希望這可以幫到
對不起,我的英語!
重定向到fbLoginUrl.AbsoluteUri – prabir 2012-03-28 20:20:02
謝謝@prabir稍後會試一試。整天都在跑步。 – Jess 2012-03-29 00:41:28