0
我完全新的MVC所以道歉,如果這是一個簡單的問題,但我用Google搜索,並不能找到答案。ASP.NET MVC返回自定義錯誤來登錄
我正在使用ASP.NET身份與谷歌提供商,這工作正常,但我想檢查,如果該用戶存在於數據庫中,只允許用戶與ExternalLoginCallback userinfo。
這是我該函數修改後的代碼:
'
' GET: /Account/ExternalLoginCallback
<AllowAnonymous>
Public Async Function ExternalLoginCallback(returnUrl As String) As Task(Of ActionResult)
Dim loginInfo = Await AuthenticationManager.GetExternalLoginInfoAsync()
If loginInfo Is Nothing Then
Return RedirectToAction("Login")
End If
' Sign in the user with this external login provider if the user already has a login
Dim result = Await SignInManager.ExternalSignInAsync(loginInfo, isPersistent := False)
Select Case result
Case SignInStatus.Success
Return RedirectToLocal(returnUrl)
Case SignInStatus.LockedOut
Return View("Lockout")
Case SignInStatus.RequiresVerification
Return RedirectToAction("SendCode", New With {
.ReturnUrl = returnUrl,
.RememberMe = False
})
Case Else
'check first if the user has an account set up with this provider email.
Dim uid = Await UserManager.FindByEmailAsync(loginInfo.Email)
If uid IsNot Nothing Then
If uid.Id <> "" Then
Dim result1 = Await UserManager.AddLoginAsync(uid.Id, loginInfo.Login)
If result1.Succeeded Then
Await SignInManager.SignInAsync(uid, isPersistent:=False, rememberBrowser:=False)
ViewBag.ReturnUrl = returnUrl
Return RedirectToLocal(returnUrl)
End If
End If
End If
Dim errmsg As String = "You are not authorised to use this account"
ModelState.AddModelError("", errmsg)
Return RedirectToAction("Login")
End Select
End Function
此代碼的工作,因爲它的用戶重定向到登錄頁面,但我想添加自定義錯誤,你可以從代碼中看到。登錄視圖有 @ Html.ValidationSummary(True,「」,New With {.class =「text-danger」})
但我的代碼我相信只適用於當前模型「ExternalLoginConfirmation」。如何在登錄視圖中獲取此自定義錯誤?
你的意思是你要顯示的'errmsg'定義,當你重定向到'登錄()'方法的消息? –
@StephenMuecke - 是的,你理解正確。 – grayson
您重定向到另一個視圖,所以ModelState.AddModelError(「」,errmsg)「是毫無意義的,除非您返回相同的視圖(只要您重定向,它就會被丟棄)。一種選擇是將消息添加到'TempData',然後在'Login()'方法中,讀取該值(如果存在)並將其添加到'ViewBag',然後在視圖中將其顯示在div元素中。 –