我是MVC的新手,如果这是一个简单的问题,请道歉,但我用Google搜索并找不到答案。
我正在使用谷歌提供商的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,&#34;&#34;,New With {.class =&#34; text-danger&#34;})
但我认为我的代码只适用于当前的模型&#34; ExternalLoginConfirmation&#34;。如何在日志视图中获得此自定义错误?
答案 0 :(得分:0)
感谢@StephenMuecke和@TheUnknown的精彩快速反应,我解决了这个问题。
我替换了
ModelState.AddModelError("", errmsg)
带
TempData("loginError") = errmsg
然后在登录操作中,我添加了:
Dim errorresult = TempData("loginError")
If errorresult IsNot Nothing Then
If errorresult <> "" Then
ViewBag.ErrorResult = errorresult
End If
End If
然后在行后的Login.vbhtml中:
@Html.Partial("_ExternalLoginsListPartial", New ExternalLoginListViewModel With {.ReturnUrl = ViewBag.ReturnUrl})
我添加了
<p class="text-danger">@ViewBag.ErrorResult</p>
它现在完美无缺。