Я занимаюсь разработкой ASP. NET приложения Web API 2.0 на основе. Net Framework 4.7 и получаю эту ошибку, когда пытаюсь отправлять электронные письма с помощью MailKit. Локально мои приложения работают нормально, но когда я публикую sh на хостинге, основанном на Windows Server 2012, я получил исключение MikeKit.ParserOptions и не могу отправлять электронные письма. Вот моя ошибка почтальона:
{
"Message": "An error has occurred.",
"ExceptionMessage": "The type initializer for 'MimeKit.ParserOptions' threw an exception.",
"ExceptionType": "System.TypeInitializationException",
"StackTrace": " at MimeKit.MimeMessage..ctor()\r\n at AgriturismoIlMelogranoNet.Controllers.EmailRequestController.Post(EmailRequest emailRequest) in C:\\Users\\magar\\source\\repos\\AgriturismoIlMelogranoNet\\AgriturismoIlMelogranoNet\\Controllers\\EmailRequestController.cs:line 20\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()",
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "The type initializer for 'MimeKit.Utils.CharsetUtils' threw an exception.",
"ExceptionType": "System.TypeInitializationException",
"StackTrace": " at MimeKit.ParserOptions..ctor()\r\n at MimeKit.ParserOptions..cctor()",
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Operation could destabilize the runtime.",
"ExceptionType": "System.Security.VerificationException",
"StackTrace": " at MimeKit.Utils.OptimizedOrdinalIgnoreCaseComparer.GetHashCode(String obj)\r\n at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)\r\n at MimeKit.Utils.CharsetUtils.AddAliases(Dictionary`2 dict, Int32 codepage, Int32 fallback, String[] names)\r\n at MimeKit.Utils.CharsetUtils..cctor()"
}
}
}
Я пытался установить System.Text.Encoding.CodePage, но это не решило мою проблему. Тогда я думал, что проблема связана с хостингом, поэтому я отредактировал свой файл web.config, добавив:
<location path="site.it" allowOverride="true">
<system.web>
<trust level="Full" originUrl="" />
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
</system.web>
</location>
Но это не помогло.
Код моего контроллера:
public IHttpActionResult Post([FromBody] EmailRequest emailRequest)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Sistema automatico", Username));
message.To.Add(new MailboxAddress(To));
message.Subject = "Richiesta da parte del cliente " + emailRequest.Name;
var bodyBuilder = new BodyBuilder();
bodyBuilder.TextBody = emailRequest.Message;
message.Body = bodyBuilder.ToMessageBody();
using (var client = new SmtpClient(/*new ProtocolLogger(Console.OpenStandardOutput())*/))
{
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
client.Connect(Host, Port, SecureSocketOptions.Auto);
// Note: only needed if the SMTP server requires authentication
client.Authenticate(Username, Password);
try
{
client.Send(message);
return Ok();
}
catch (Exception)
{
return BadRequest();
}
finally
{
client.Disconnect(true);
}
}
}
Есть идеи? Мой хостинг провайдер иль называется Аруба. Спасибо