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

VB.NET网站集成SendGrid无法发信且后台无记录问题求助

问题排查与解决方案

核心问题点

  • 异步调用死锁:你在ASP.NET Web Forms的同步事件处理方法中使用Wait()阻塞异步方法,ASP.NET默认的同步上下文会导致死锁,异步发信请求永远无法执行完成,所以SendGrid后台没有收到任何请求记录。
  • 异常被静默吞掉:Catch块中仅使用Console.WriteLine输出异常,线上Web环境无控制台输出,所有运行错误(比如ApiKey读取失败、网络不通)都无法被感知。
  • 缺少页面异步支持:Web Forms页面默认未开启异步处理,直接调用异步方法会出现上下文不匹配问题。

修复步骤

1. 调整页面配置

在admin_sendgrid.aspx页面头部的Page指令中添加Async="True",开启页面异步支持:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="admin_sendgrid.aspx.vb" Inherits="admin_sendgrid" Async="True" %>

2. 重构发信代码,移除死锁写法

删除不必要的Main方法,直接异步调用发信逻辑,同时优化异常处理:

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Configuration
Imports SendGrid
Imports SendGrid.Helpers.Mail

Class sendgrid1
    Public Async Function TestSendGrid(ByVal test As String) As Task(Of String)
        Try
            Dim apiKey = ConfigurationManager.AppSettings("ApiKey")
            ' 先校验ApiKey是否读取成功
            If String.IsNullOrEmpty(apiKey) Then
                Return "错误:未读取到ApiKey配置"
            End If
            Dim client = New SendGridClient(apiKey)
            Dim msg = New Helpers.Mail.SendGridMessage() With {
                .From = New EmailAddress("admin@pacificwestcapital.net", test),
                .Subject = "Hello World from the SendGrid VB.NET SDK!",
                .PlainTextContent = "Hello, Email!",
                .HtmlContent = "<strong>Hello, Email!</strong>"
            }
            msg.AddTo(New EmailAddress("pacwestcapital@aol.com", "Scot King"))
            Dim response = Await client.SendEmailAsync(msg)
            ' 返回响应状态码方便排查
            Return $"发送成功,状态码:{response.StatusCode}"
        Catch ex As Exception
            ' 返回完整异常信息
            Return $"发送失败:{ex.ToString()}"
        End Try
    End Function
End Class

Partial Class admin_sendgrid
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

    End Sub
    ' 将点击事件改为异步方法
    Protected Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim sg As New sendgrid1
        Dim result = Await sg.TestSendGrid("Scot King")
        ' 这里可以把result绑定到页面Label上显示,方便排查问题
        ' 例如:Label1.Text = result
    End Sub
End Class

3. 验证前置配置

  • 确认线上web.config的<appSettings>节点下存在正确的ApiKey配置,大小写和代码中读取的键名完全一致
  • 确认发件人邮箱admin@pacificwestcapital.net已经在SendGrid后台完成单邮箱验证或者域名验证
  • 确认线上服务器的出站端口443没有被防火墙拦截,允许访问SendGrid的API接口

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:15:09