You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC(VB.NET)集成微软单点登录时AuthenticationFailed委托参数错误求助

解决ASP.NET MVC VB.NET中OpenIdConnect AuthenticationFailed委托赋值错误

这个错误的核心原因是你在VB.NET里错误地调用了方法(加了()),而不是传递方法的委托引用给AuthenticationFailed属性,同时你的方法返回类型也不符合委托的要求,我来一步步帮你修正:

问题1:委托引用传递错误

在C#中,我们可以直接用方法组(比如OnAuthenticationFailed)来赋值给委托类型的属性,但VB.NET需要使用AddressOf关键字来获取方法的委托引用,而不是加括号执行方法。你原来写的OnAuthenticationFailed()是在试图执行这个方法,而不是把它作为委托传递给AuthenticationFailed事件。

问题2:方法返回类型不匹配

OpenIdConnectAuthenticationNotifications.AuthenticationFailed要求的委托返回类型是Task,但你当前的方法返回的是Task(Of Integer),这会导致类型不兼容,需要修正返回类型。

修正后的完整代码

'Configure OWIN to use OpenIdConnect
Public Sub Configuration(app As IAppBuilder)
    ' app.SanitizeThreadCulture()
    app.MapSignalR()
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
    app.UseCookieAuthentication(New CookieAuthenticationOptions())
    app.UseOpenIdConnectAuthentication(New OpenIdConnectAuthenticationOptions With {
        .ClientId = clientId,
        .Authority = authority,
        .RedirectUri = redirectUri,
        .PostLogoutRedirectUri = redirectUri,
        .Scope = OpenIdConnectScope.OpenIdProfile,
        .ResponseType = OpenIdConnectResponseType.CodeIdToken,
        .TokenValidationParameters = New TokenValidationParameters() With {
            .ValidateIssuer = False
        },
        .Notifications = New OpenIdConnectAuthenticationNotifications With {
            ' 这里用AddressOf传递委托引用,而不是调用方法
            .AuthenticationFailed = AddressOf OnAuthenticationFailed
        }
    })
End Sub

'Handle failed authentication requests by redirecting the user to the home page with an error in the query string
' 修正返回类型为Task,符合委托要求
Private Function OnAuthenticationFailed(ByVal context As AuthenticationFailedNotification(Of OpenIdConnectMessage, OpenIdConnectAuthenticationOptions)) As Threading.Tasks.Task
    context.HandleResponse()
    context.Response.Redirect("/?errormessage=" & context.Exception.Message)
    ' 返回Task.CompletedTask代替Task.FromResult(0)
    Return Threading.Tasks.Task.CompletedTask
End Function

额外说明

  • AddressOf是VB.NET中获取方法委托引用的标准方式,它告诉编译器你要传递的是方法本身,而不是方法执行后的结果。
  • 将返回类型改为Task并返回Task.CompletedTask,是因为AuthenticationFailed事件处理程序不需要返回具体的数值,只需要表示异步操作完成即可。

内容的提问来源于stack exchange,提问作者PlasmaX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 21:17:31