我正在try 根据这https://www.ryadel.com/en/asp-net-core-send-email-messages-sendgrid-api/个教程创建一个控制器

除了控制器之外,我已经添加了所有内容.控制器中的代码是

public class SendGridController : BaseApiController
{
    private readonly IEmailSender _emailSender;
    public SendGridController(IEmailSender emailSender)
    {
        _emailSender = emailSender;
        
    }

    [HttpPost]
    [ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)]
    [ProducesResponseType(typeof(string), (int)HttpStatusCode.BadRequest)]
    [ProducesResponseType((int)HttpStatusCode.Unauthorized)]
    [ProducesResponseType(typeof(string), (int)HttpStatusCode.InternalServerError)]
    public async Task<ActionResult> SendEmail() {
        await _emailSender.SendEmailAsync("test@mail.com", "subject", "something");
        return Ok(await _emailSender.SendEmailAsync("test@mail.com", "subject", "something"));
    }
}

但我发现以下错误

Argument 1: cannot convert from 'void' to 'object'

我希望能够看到来自发送网格的响应,如果它已经发送或没有.

以下是SendGridEmailSender类:

public class SendGridEmailSender : IEmailSender
{
    public SendGridEmailSender(
        IOptions<SendGridEmailSenderOptions> options
        )
    {
        this.Options = options.Value;
    }

    public SendGridEmailSenderOptions Options { get; set; }

    public async Task SendEmailAsync(
        string email, 
        string subject, 
        string message)
    {
        await Execute(Options.ApiKey, subject, message, email);
    }

    private async Task<Response> Execute(
        string apiKey, 
        string subject, 
        string message, 
        string email)
    {
        var client = new SendGridClient(apiKey);
        var msg = new SendGridMessage()
        {
            From = new EmailAddress(Options.SenderEmail, Options.SenderName),
            Subject = subject,
            PlainTextContent = message,
            HtmlContent = message
        };
        msg.AddTo(new EmailAddress(email));

        // disable tracking settings
        // ref.: https://sendgrid.com/docs/User_Guide/Settings/tracking.html
        msg.SetClickTracking(false, false);
        msg.SetOpenTracking(false);
        msg.SetGoogleAnalytics(false);
        msg.SetSubscriptionTracking(false);

        return await client.SendEmailAsync(msg);
    }
}

推荐答案

您没有返回private方法的结果:

await Execute(Options.ApiKey, subject, message, email);

因此,您需要返回结果

public async Task SendEmailAsync(
    string email, 
    string subject, 
    string message)
{
    result = await Execute(Options.ApiKey, subject, message, email);
    // do some checks with result
}

如果需要在控制器代码中判断结果,则会更加棘手,因为IEmailSender的签名不提供通用任务对象,需要手动转换(不建议这样做).您可以简单地假设在方法完成后发送成功(因为在其他情况下,您会得到异常):

public async Task<ActionResult> SendEmail() {
    await _emailSender.SendEmailAsync("test@mail.com", "subject", "something");
    // email was sent, no exception
    return Ok();
}

如果您需要该方法的响应,可以使用_emailSender.SendEmailAsync("test@mail.com", "subject", "something")执行类似于this answer的操作,而不使用await构造(仍然不能推荐这种方法):

/// <summary> 
/// Casts a <see cref="Task"/> to a <see cref="Task{TResult}"/>. 
/// This method will throw an <see cref="InvalidCastException"/> if the specified task 
/// returns a value which is not identity-convertible to <typeparamref name="T"/>. 
/// </summary>
public static async Task<T> Cast<T>(this Task task)
{
    if (task == null)
        throw new ArgumentNullException(nameof(task));
    if (!task.GetType().IsGenericType || task.GetType().GetGenericTypeDefinition() != typeof(Task<>))
        throw new ArgumentException("An argument of type 'System.Threading.Tasks.Task`1' was expected");

    await task.ConfigureAwait(false);

    object result = task.GetType().GetProperty(nameof(Task<object>.Result)).GetValue(task);
    return (T)result;
}

Asp.net相关问答推荐

如何在 asp.net 服务器中使用字体

强制从 /bin 而不是 GAC 加载程序集?

如何向 Array.IndexOf 添加不区分大小写的选项

SignalR + Autofac + OWIN:为什么 GlobalHost.ConnectionManager.GetHubContext 不起作用?

在哪里可以记录 ASP.NET Core 应用程序的启动/停止/错误事件?

.NET 站点如何隐藏其文件的 .aspx 扩展名?

我可以根据角色隐藏/显示 asp:Menu 项吗?

如何在没有实体框架的情况下使用 ASP.NET Identity 3.0

在使用网络服务器加载它们之前,如何编译 Asp.Net Aspx 页面?

如何验证文件上传的文件类型?

ASP.NET Core 2.0 为同一端点结合了 Cookie 和承载授权

您如何在 .net WebApi2 应用程序中的 OAuth2 令牌请求中使用额外参数

对于 DB ID,需要一个较小的 GUID 替代方案,但对于 URL 仍然是唯一且随机的

ASP.NET 按钮重定向到另一个页面

如何在 asp.net 中实现Access-Control-Allow-Origin标头

~/ 等价于 javascript

可以在不 destruct 站点的情况下将 MIME 类型添加到 web.config 吗?

强制 IIS Express 进入classic 管道模式

如何创建代表 colored颜色 的随机十六进制字符串?

ASP.NET 自定义控件 - 未知的服务器标记