我遇到了问题。当我在开发服务器上提交表单时,它可以按预期工作。当我部署该应用程序( asp.net core 2.1 mvc app
)并尝试提交该表单时,该表单挂起了好一会儿,然后我得到一个状态码为500的空白页面。
关于这一切的任何线索吗?
下面是我最近在项目中添加的代码。它提交表单并通过电子邮件发送结果。我正在使用ReCapcha,如果有什么不同吗?
[ValidateAntiForgeryToken]
[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> ContactMe([FromForm] Contact model)
{
if (ModelState.IsValid)
{
if (!await GoogleRecaptchaHelper.IsReCaptchaPassedAsync(Request.Form["g-recaptcha-response"],
_configuration["GoogleReCaptcha:secret"]))
{
ModelState.AddModelError(string.Empty, "You failed the CAPTCHA");
TempData["message"] = $"Sorry {model.SenderName}, You failed the CAPTCHA";
TempData["messageClass"] = "alert alert-danger";
return View("Contact", model);
}
try
{
var smtpClient = new SmtpClient
{
Host = "auth.smtp.1and1.co.uk",
EnableSsl = true,
Credentials = new NetworkCredential(@"no-reply@griffithswebdesign.com", "totimen"),
};
using (var message = new MailMessage("no-reply@griffithswebdesign.com", "michael@griffithswebdesign.com")
{
Subject = "Message from " + model.SenderName + " - ROOTWORKS Website",
ReplyToList = { new MailAddress(model.SenderEmail) },
IsBodyHtml = true,
Body = "<h2 style=\"text-align:center\">Message from ROOTWORKS</h2><p><strong>From:</strong> " + model.SenderName + "</p><p>" + model.MessageContent + "</p>"
})
{
smtpClient.Send(message);
TempData["message"] = $"Thank you {model.SenderName}, your message has been sent and someone will be in touch soon.";
TempData["messageClass"] = "alert alert-success";
}
}
catch (Exception)
{
TempData["message"] = $"Sorry {model.SenderName}, something has gone wrong and your message has not been sent. Please try again later.";
TempData["messageClass"] = "alert alert-danger";
}
return RedirectToRoute("contactroute");
}
return RedirectToRoute("contactroute");
}
}
********************编辑****************************
那是在我的控制器中。 我也有Google recapcha的助手
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Net.Http;
namespace Rootworks.Helpers
{
public static class GoogleRecaptchaHelper
{
// A function that checks reCAPTCHA results
public static async Task<bool> IsReCaptchaPassedAsync(string gRecaptchaResponse, string secret)
{
HttpClient httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("secret", secret),
new KeyValuePair<string, string>("response", gRecaptchaResponse)
});
var res = await httpClient.PostAsync($"https://www.google.com/recaptcha/api/siteverify", content);
if (res.StatusCode != HttpStatusCode.OK)
{
return false;
}
string JSONres = res.Content.ReadAsStringAsync().Result;
dynamic JSONdata = JObject.Parse(JSONres);
if (JSONdata.success != "true")
{
return false;
}
return true;
}
}
}
在进一步调查中,我发现出现以下错误:
SocketException:连接尝试失败,因为已连接 一段时间后未正确响应,或已建立 连接失败,因为连接的主机无法响应 System.Net.Http.ConnectHelper.ConnectAsync(字符串主机,整数端口, CancellationToken cancellingToken)
此外,这是我的startup.cs代码-如果发生了某些事情:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Rootworks
{
public class Startup
{
public IHostingEnvironment HostingEnvironment { get; private set; }
public IConfiguration Configuration { get; private set; }
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
this.HostingEnvironment = env;
this.Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
services.AddSession();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//if (env.IsDevelopment())
//{
app.UseDeveloperExceptionPage();
//}
//app.UseHsts();
app.UseSession();
//app.UseHttpsRedirection();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
app.UseMvc(routes =>
{
routes.MapRoute(
name: null,
template: "about-smp",
defaults: new { Controller = "Home", action = "Aboutsmp" }
);
routes.MapRoute(
name: null,
template: "the-founder",
defaults: new { Controller = "Home", action = "Aboutfounder" }
);
routes.MapRoute(
name: null,
template: "how-rootworks-are-different",
defaults: new { Controller = "Home", action = "Whyme" }
);
routes.MapRoute(
name: null,
template: "the-treatments",
defaults: new { Controller = "Home", action = "Treatments" }
);
routes.MapRoute(
name: "contactroute",
template: "contact",
defaults: new { Controller = "Home", action = "ContactMe" }
);
routes.MapRoute(
name:null,
template:"faq",
defaults: new { Controller = "Home", action = "FAQ"}
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}