SmtpClient异常导致WebApi通过Owin永远不会返回

时间:2016-12-21 08:31:32

标签: c# asp.net asp.net-web-api

我面临着一个非常奇怪的问题,我希望有人会有解决方案。我通过Owin用Owin和WebApi创建了一个ASP.NET Web应用程序。

我创建了一个显示问题的Git仓库:https://github.com/robbaman/smtp-error-example

代码

Startup.cs

public class Startup {
    public void Configuration(IAppBuilder app) {
        var config = new HttpConfiguration();
        config.MapHttpAttributeRoutes();
        app.UseWebApi(config);
    }
}

TestController.cs

public class TestController : ApiController {

    [HttpGet, Route("test")]
    public void Test() {
        using (var client = new SmtpClient()) {
            var message = new MailMessage();
            message.To.Add("test@example.com");
            message.Body = "haha";
            message.Subject = "ohhh";
            client.Send(message);
        }
    }

    [HttpGet, Route("testasync")]
    public async Task TestAsync() {
        using (var client = new SmtpClient()) {
            var message = new MailMessage();
            message.To.Add("test@example.com");
            message.Body = "haha";
            message.Subject = "ohhh";
            await client.SendMailAsync(message);
        }
    }

    [HttpGet, Route("test2")]
    public async Task Test2() {
        throw new NotImplementedException();
    }
}

使用Nuget包

  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.AspNet.WebApi.Owin

Web.config Smtp部分

<system.net>
    <mailSettings>
        <smtp from="support@example.com">
            <network host="mailserver" enableSsl="true" userName="support@example.com" 
                     port="587" password="password" />
        </smtp>
    </mailSettings>
</system.net>

症状

使用上面的配置(或检查GitHub repo)并运行应用程序时,会发生一些奇怪的事情:

导航到/test时,您会收到mailserver主机名无效的预期异常。导航到/test2时,您会获得预期的NotImplementedException

但是导航到/testasync时,会发生相同的主机名异常,但是没有响应发送到浏览器。它将继续加载和加载...我不知道为什么或如何解决它。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您可以像这样打电话给TestAsync() -

[HttpGet, Route("testasync")]
public string CallTestAsync()
{
    Task t = TestAsync();
    string response = "";

    if (t.IsFaulted)
    {
        response = t.Exception.InnerException.Message;
    }
    else
    {
        response = "Success";
    }
    return response;
}

[HttpGet, Route("testasync")]

中删除属性TestAsync()