我正在使用DotNetOpenAuth與自定義登錄提供程序簽署用戶到我的網站。我的大部分代碼都可以工作,但遇到問題時會返回視圖並顯示它,以便用戶可以登錄到提供程序。基本上,該操作將返回一個actionresult,它是特定提供程序上的登錄頁面,返回到調用JavaScript。我期待這一點,因爲我需要將登錄結果返回給javascript。基本上,會發生什麼是我得到一些錯誤,關於允許訪問然後三個空框(查看電話的返回),然後什麼都沒有。我需要它轉到提供商站點並登錄。ASP.NET MVC - 如何顯示返回到JavaScript的「ActionResult」視圖?
數據示例:url = https://www.google.com/accounts/o8/id,requiresUserName = false,username = test(假定它已輸入到文本框中)。
下面是代碼:
的JavaScript:
function ProviderSignOn(url, requiresUserName) {
var username = $("#openUserNameText").val();
if ((requiresUserName == 'True') && (username == '')) {
clickedProviderUrl = url;
$('#openUserNameDiv').show('fast');
}
else {
$('#openUserNameDiv').hide('fast');
$("#openUserNameText").val('');
$.ajax({
type: "POST",
url: "/Account/ProviderSignOn",
data: "provider=" + url + "&username=" + username,
success: function (data) {
alert(data.Error);
alert(data.Message);
alert(data.Identifier);
},
failure: function (data) {
alert(data.Error);
alert(data.Message);
alert(data.Identifier);
}
});
}
}
控制器動作:
public ActionResult ProviderSignOn(string provider, string username)
{
string providerUrl = provider.Replace("{username}", username);
bool error = true;
string message = String.Empty;
string identifier = String.Empty;
var response = _openId.GetResponse();
if (response == null)
{
Identifier id;
if (Identifier.TryParse(providerUrl, out id))
{
try
{
return _openId.CreateRequest(providerUrl).RedirectingResponse.AsActionResult();
}
catch (ProtocolException ex)
{
throw ex;
}
}
else
{
error = true;
message = "Invalid";
identifier = String.Empty;
}
}
else
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
error = false;
message = "Success";
identifier = response.ClaimedIdentifier;
break;
case AuthenticationStatus.Canceled:
error = true;
message = "Canceled";
identifier = String.Empty;
break;
case AuthenticationStatus.Failed:
error = true;
message = "Failed";
identifier = String.Empty;
break;
}
}
return Json(new { Error = error, Message = message, Identifier = identifier });
}
我注意到你在錯誤的情況下返回JSON。我通常不會提出這個建議。相反,拋出一個異常。除非Json包含您計劃向用戶顯示的數據,否則可以引發異常,然後使用jQuery'$ .ajax'的'error'選項。 – Domenic 2010-11-01 20:50:12
另外請注意,它是'error',而不是'failure':http://api.jquery.com/jQuery.ajax/ – Domenic 2010-11-01 20:50:28
是的,這只是讓我通過atm搞清楚如何處理這個調用的代碼。我最終會改變它來做實際的事情,只是想在那裏有一些調試的東西。感謝您的建議。 – Dave 2010-11-01 20:59:24