我正在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相关问答推荐

如何从 Azure 上托管的应用服务获取登录用户名?

我可以强制刷新我的样式表文件吗?

如何在没有 Select 按钮的情况下在 GridView 中实现全行 Select ?

如何调试 Azure 500 内部服务器错误

在每页级别增加 ASP.Net 超时

静态字段与会话变量

asp.net dropdownlist - 在 db 值之前添加空行

有没有一种简单的方法可以将对象属性转换为字典

如何从网页 (asp.net) 启动 EXE

由于缺少定义,在 .net Core 应用程序上构建失败

Response.Redirect 使用 ~ 路径

AddDefaultTokenProviders:它是什么以及如何使用那些默认提供者?

如何在 ASP.NET Core Web API 中配置 JSON 格式的缩进

HttpResponse.End 或 HttpResponse.Close 与 HttpResponse.SuppressContent

ASP.net 中是否有 after Page_Load 事件

MVC 模型布尔显示是或否

远程计算机无法连接到 Visual Studio Web 服务器

在 ASP.NET 标识中添加角色

配置授权服务器端点

ConfigurationManager.AppSettings 缓存