在 session_start 上发送邮件

Send mail on session_start

我想调用 session_start 中的方法(发送邮件)。 这是我的任务函数:

    Public Shared Async Function SendEmailMessage(ByVal MailFrom As String, ByVal MailTo As String, ByVal Subject As String, ByVal HtmlMessage As String) As Task

    Dim mail As MailMessage = New MailMessage


    mail.From = New MailAddress(MailFrom)

    mail.To.Add(MailTo)

    mail.Subject = Subject

    mail.Body = HtmlMessage

    Dim smtp As SmtpClient = New SmtpClient("smtpclient")
    smtp.Port = 587
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network
    smtp.UseDefaultCredentials = True

    Await Task.Run(Function() smtp.SendMailAsync(mail))

    'Await result

End Function

在 global.asax 我有这个代码:

Public Overrides Sub Init()
    MyBase.Init()
    Dim wrapper = New EventHandlerTaskAsyncHelper(AsyncSessionStart)
    Me.AddOnAcquireRequestStateAsync(wrapper.BeginEventHandler, wrapper.EndEventHandler)
End Sub


Private Async Function AsyncSessionStart() As Task
    If Not Session.IsNewSession Then Return
    Await funzioni.SendEmailMessage("***@***.**", "*****@***", "Object text",
                                                    String.Format("E' stato effettuato un tentativo di accesso da {0} del {1} alla WebApp.",
                                                                  Session("name"), Session("office")))
End Function

这是我阅读并遵循的参考文本asp-net-async-global-asax

visual studio,但是,在这部分代码中出现以下错误:

Dim wrapper = New EventHandlerTaskAsyncHelper(AsyncSessionStart)

无法将任务类型的值转换为 TaskEventHandler。

我哪里错了?

未经测试,我认为:

Private Async Function AsyncSessionStart() As Task

应该是这样的:

Private Async Sub AsyncSessionStart(sender As Object, e As EventArgs)

您指定给 EventHandlerTaskAsyncHelper 构造函数的方法应该是一个异步事件处理程序,这意味着使用标准事件处理程序参数(您发布的 link 有但您忽略了)并声明它一个 Async Sub.

您还必须使用 AddressOf 运算符在 VB 中创建委托。您可能还必须明确指定委托类型:

Dim wrapper = New EventHandlerTaskAsyncHelper(AddressOf AsyncSessionStart)

或:

Dim wrapper = New EventHandlerTaskAsyncHelper(New TaskEventHandler(AddressOf AsyncSessionStart))