Blazor WebAssembly调用SendGrid发送邮件遭遇CORS错误求助
解决Blazor WebAssembly中调用SendGrid API的CORS错误
问题根源
- CORS限制:SendGrid的API服务器仅允许特定域名(如官方文档站点)跨域访问,你的
http://localhost:50855不在允许列表内,因此触发CORS拦截。 - 安全风险:直接在Blazor WASM前端代码中硬编码SendGrid API Key是致命错误——前端代码完全公开,任何人都能获取你的密钥并滥用发送邮件权限。
正确解决方案:后端代理请求
必须将SendGrid调用逻辑移至后端服务(如ASP.NET Core Web API),前端仅调用自有后端接口,由后端完成与SendGrid的交互。
1. 创建后端API接口
在ASP.NET Core项目中添加邮件控制器:
using Microsoft.AspNetCore.Mvc; using SendGrid; using SendGrid.Helpers.Mail; [ApiController] [Route("api/email")] public class EmailController : ControllerBase { private readonly IConfiguration _config; public EmailController(IConfiguration config) => _config = config; [HttpPost("send")] public async Task<IActionResult> SendEmail([FromBody] EmailRequest request) { var client = new SendGridClient(_config["SendGrid:ApiKey"]); var from = new EmailAddress(request.FromEmail, request.FromName); var to = new EmailAddress(request.ToEmail, request.ToEmail); var msg = MailHelper.CreateSingleEmail(from, to, request.Subject, request.PlainTextContent, request.HtmlContent); var response = await client.SendEmailAsync(msg); return response.IsSuccessStatusCode ? Ok() : BadRequest("邮件发送失败"); } } public class EmailRequest { public string FromEmail { get; set; } public string FromName { get; set; } public string ToEmail { get; set; } public string Subject { get; set; } public string PlainTextContent { get; set; } public string HtmlContent { get; set; } }
2. 配置SendGrid密钥
在appsettings.json中安全存储密钥(避免硬编码):
{ "SendGrid": { "ApiKey": "你的SendGrid API密钥" } }
3. Blazor前端调用后端接口
修改Blazor组件代码,调用自有后端API:
using System.Net.Http.Json; // 组件内的发送逻辑 var emailRequest = new { FromEmail = "portfolio1005@gmail.com", FromName = "From Name", ToEmail = "portfolio1005@gmail.com", Subject = "sub", PlainTextContent = "any body", HtmlContent = "any body" }; var httpClient = HttpClient; // 使用Blazor注入的HttpClient var response = await httpClient.PostAsJsonAsync("/api/email/send", emailRequest); return response.IsSuccessStatusCode;
4. 配置后端CORS
确保后端允许Blazor应用的域名跨域访问,在Program.cs中添加:
builder.Services.AddCors(options => { options.AddPolicy("AllowBlazor", policy => policy.WithOrigins("http://localhost:50855") .AllowAnyHeader() .AllowAnyMethod()); }); // ... app.UseCors("AllowBlazor");
内容的提问来源于stack exchange,提问作者Abdussalam Ashuaebi
相关产品推荐
相关产品推荐

