C# 发送电子邮件并将其保存在数据库中(ASP.NET MVC)

C# 发送电子邮件并将其保存在数据库中(ASP.NET MVC),c#,asp.net-mvc,C#,Asp.net Mvc,我一直在使用ASP.NETMVC开发一个网站,在这个网站上,你可以直接向特定的电子邮件地址发送电子邮件。它工作正常,但电子邮件中发送的信息(如姓名、电子邮件地址等)没有数据库。所以我试着为它添加一个数据库,但不知怎么的,它不起作用,我一直有一些错误。我刚刚接触过这种东西,所以我不确定是否可以发送电子邮件并同时将其保存到数据库中。我知道我现在做的有些不对劲,所以请有人帮帮我。多谢各位 这是我发送电子邮件的控制器: [HttpPost] [ValidateAntiForgeryTok

我一直在使用ASP.NETMVC开发一个网站,在这个网站上,你可以直接向特定的电子邮件地址发送电子邮件。它工作正常,但电子邮件中发送的信息(如姓名、电子邮件地址等)没有数据库。所以我试着为它添加一个数据库,但不知怎么的,它不起作用,我一直有一些错误。我刚刚接触过这种东西,所以我不确定是否可以发送电子邮件并同时将其保存到数据库中。我知道我现在做的有些不对劲,所以请有人帮帮我。多谢各位

这是我发送电子邮件的控制器:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(TalentInfo model, IEnumerable<HttpPostedFileBase> files)
    {
        if (ModelState.IsValid)
        {
            RegisterRepository regRepo = new RegisterRepository();

            if (regRepo.Register(model))
            {
                List<string> paths = new List<string>();

                foreach (var file in files)
                {
                    if (file.ContentLength > 0)
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                        file.SaveAs(path);
                        paths.Add(path);
                    }
                }

                var message = new MailMessage();
                foreach (var path in paths)
                {
                    var fileInfo = new FileInfo(path);
                    var memoryStream = new MemoryStream();
                    using (var stream = fileInfo.OpenRead())
                    {
                        stream.CopyTo(memoryStream);
                    }
                    memoryStream.Position = 0;
                    string fileName = fileInfo.Name;
                    message.Attachments.Add(new Attachment(memoryStream, fileName));
                }

                //Rest of business logic here
                string EncodedResponse = Request.Form["g-Recaptcha-Response"];
                bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
                if (IsCaptchaValid)
                {

                    var body = "<p><b>Email From:</b> {0} ({1})</p><p><b>Message:<b></p><p>{2}</p>";
                    message.To.Add(new MailAddress("***@gmail.com"));  // replace with valid value 
                    message.From = new MailAddress("***@ymailcom");  // replace with valid value
                    message.Subject = "YesDubai.org (REGISTRATION)";
                    message.Body = string.Format(body, model.Talent_Name, model.Talent_Email, model.Talent_SelfPromotion);
                    message.IsBodyHtml = true;
                    using (var smtp = new SmtpClient())
                    {
                        var credential = new NetworkCredential
                        {
                            UserName = "***@gmail.com",  // replace with valid value
                            Password = "***"  // replace with valid value
                        };
                        smtp.Credentials = credential;
                        smtp.Host = "smtp.gmail.com";
                        smtp.Port = 587;
                        smtp.EnableSsl = true;
                        smtp.SendCompleted += (s, e) =>
                        {
                            //delete attached files
                            foreach (var path in paths)
                                System.IO.File.Delete(path);
                        };
                        await smtp.SendMailAsync(message);
                        ViewBag.Message = "Your message has been sent!";

                        ModelState.Clear();
                        return View("Register");
                    }
                }
                else
                {
                    TempData["recaptcha"] = "Please verify that you are not a robot!";
                }

            } return View(model);

        }
    }
这是存储库:

public class RegisterRepository
{

    //SqlTransaction transaction = null;
    private SqlConnection con;
    //To Handle connection related activities
    private void connection()
    {
        string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
        con = new SqlConnection(constr);


    }


    internal bool Register(TalentInfo model)
    {
        throw new NotImplementedException();

        connection();

        try
        {
            SqlCommand com = new SqlCommand("SP_INSERT_TALENT_INFO", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@Talent_name", model.Talent_Name);
            com.Parameters.AddWithValue("@Talent_email", model.Talent_Email);
            com.Parameters.AddWithValue("@Talent_SelfPromotion", model.Talent_SelfPromotion);
            con.Open();
            int i = com.ExecuteNonQuery();
            con.Close();
            if (i >= 1)
            {
                return true;
            }
            else
            {

                return false;
            }


        }

        catch
        {
            return Register(model);
        }
        finally
        {
            con.Close();
        }

    }


}

这只是一个编译错误。您需要在代码的所有路径中返回结果

这里缺少一个
返回值

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(TalentInfo model, IEnumerable<HttpPostedFileBase> files)
{
    if (ModelState.IsValid)
    {
        //you have lots of code here....
    }
    else
    {
        //you need to return something here....because (ModelState.IsValid) might be false
    }
}
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务寄存器(TalentInfo模型,IEnumerable文件)
{
if(ModelState.IsValid)
{
//这里有很多代码。。。。
}
其他的
{
//您需要在此处返回某些内容…因为(ModelState.IsValid)可能为false
}
}

这只是一个编译错误。您需要在代码的所有路径中返回结果

这里缺少一个
返回值

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(TalentInfo model, IEnumerable<HttpPostedFileBase> files)
{
    if (ModelState.IsValid)
    {
        //you have lots of code here....
    }
    else
    {
        //you need to return something here....because (ModelState.IsValid) might be false
    }
}
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务寄存器(TalentInfo模型,IEnumerable文件)
{
if(ModelState.IsValid)
{
//这里有很多代码。。。。
}
其他的
{
//您需要在此处返回某些内容…因为(ModelState.IsValid)可能为false
}
}

您的代码中有两个错误:

1) 当if(ModelState.IsValid)的计算结果为false时返回某些内容

2) 在寄存器方法中,删除此行:

throw new NotImplementedException();

您的代码中有2个错误:

1) 当if(ModelState.IsValid)的计算结果为false时返回某些内容

2) 在寄存器方法中,删除此行:

throw new NotImplementedException();

错误是什么?粘贴it@AbdulRehmanSayedTalentInfo,System.Collections.Generic.IEnumerable'):并非所有代码路径都返回值谢谢您的帮助,先生。如果(ModelState.IsValid)的计算结果为false,则Register方法不会返回任何值。作为站点注意:重构控制器注册方法。@AbdulRehmanSayed错误已修复,先生。非常感谢。电子邮件已正确发送,但不知怎的,它没有保存在数据库中。希望你能帮助我,先生。谢谢。有什么错误吗?粘贴it@AbdulRehmanSayedTalentInfo,System.Collections.Generic.IEnumerable'):并非所有代码路径都返回值谢谢您的帮助,先生。如果(ModelState.IsValid)的计算结果为false,则Register方法不会返回任何值。作为站点注意:重构控制器注册方法。@AbdulRehmanSayed错误已修复,先生。非常感谢。电子邮件已正确发送,但不知怎的,它没有保存在数据库中。希望你能帮助我,先生。谢谢,谢谢,错误已经纠正了,先生。电子邮件已正确发送,但不知怎的,它没有保存在数据库中。希望你能帮助我,先生。谢谢,谢谢,错误已经纠正了,先生。电子邮件已正确发送,但不知怎的,它没有保存在数据库中。希望你能帮助我,先生。谢谢。我已经这样做了,先生,但是当我试图运行它时,出现了一个本地主机拒绝连接错误。您知道如何解决这个错误吗,先生?谢谢。我已经这样做了,先生,但是当我试图运行它时,出现了一个本地主机拒绝连接错误。您知道如何解决这个错误吗,先生?非常感谢。