Почему мой smtp SendMail запрещает вход в систему функций на главном сайте?

Я работаю в asp.net с C#, и я решил создать модуль всплывающих сообщений. Я сделал это на предыдущих проектах; однако, я никогда не использовал его на сайте, который также использовал Identity Framework или размещался на моей главной странице. Я также довольно новичок в C#.

Похоже, мессенджер работает нормально. Однако теперь любая функция "отправить" или "отправить", найденная на главной странице, не будет работать должным образом. Например, если я попытаюсь войти в систему как администратор, я получу свои сообщения об ошибках Windows для проверки поля в мессенджере. Я попытался удалить RequiredFieldValidators, я все еще не мог войти, вместо этого он попытался отправить сообщение.

Затем я попытался переместить модуль в пользовательский контроль и запустить его таким образом, но все же не повезло. Я подумывал о создании новой мастер-страницы для страницы входа, чтобы я мог удалить "контакт" из навигации на этой странице, устраняя тем самым проблему. Однако я бы предпочел не делать этого. Я уверен, что есть простое решение, чтобы исправить это, и мой недостаток опыта в C# не очень помогает.

Вот часть навигации на моем Site.Master, просто чтобы дать представление о том, что я делаю:

    <li><a runat="server" href="#" data-toggle="modal" data-target=".pop-up-1">Contact</a></li>
                </ul>
                <asp:LoginView runat="server" ViewStateMode="Disabled">
                    <AnonymousTemplate>
                        <ul class="nav navbar-nav navbar-right">
                            <li><a runat="server" href="~/Account/Login" style="color:#f46de6">Admin</a></li>
                            <li><asp:HyperLink ID="PayPalViewCart" runat="server" NavigateUrl=<%# Link.ToPayPalViewCart() %> style="color:#f46de6">View Cart</asp:HyperLink></li>
                        </ul>
                    </AnonymousTemplate>
                    <LoggedInTemplate>
                        <ul class="nav navbar-nav navbar-right">
                            <li><a runat="server" href="~/Account/Manage" title="Manage your account" style="color:#f46de6" >Hello, Admin</a></li>
                            <li>
                                <asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Log off" LogoutPageUrl="~/" OnLoggingOut="Unnamed_LoggingOut" />
                            </li>
                        </ul>
                    </LoggedInTemplate>
                </asp:LoginView>
            </div>
        </div>
    </div>
    <uc1:popup1 runat="server" id="popup1" />
    <div class="container body-content">

Теперь вот код на этой странице, site.Master.cs:

    public partial class SiteMaster : MasterPage
{
    private const string AntiXsrfTokenKey = "__AntiXsrfToken";
    private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
    private string _antiXsrfTokenValue;

    protected void Page_Init(object sender, EventArgs e)
    {
        // The code below helps to protect against XSRF attacks
        var requestCookie = Request.Cookies[AntiXsrfTokenKey];
        Guid requestCookieGuidValue;
        if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
        {
            // Use the Anti-XSRF token from the cookie
            _antiXsrfTokenValue = requestCookie.Value;
            Page.ViewStateUserKey = _antiXsrfTokenValue;
        }
        else
        {
            // Generate a new Anti-XSRF token and save to the cookie
            _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
            Page.ViewStateUserKey = _antiXsrfTokenValue;

            var responseCookie = new HttpCookie(AntiXsrfTokenKey)
            {
                HttpOnly = true,
                Value = _antiXsrfTokenValue
            };
            if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
            {
                responseCookie.Secure = true;
            }
            Response.Cookies.Set(responseCookie);
        }

        Page.PreLoad += master_Page_PreLoad;
    }

    protected void master_Page_PreLoad(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Set Anti-XSRF token
            ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
            ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
        }
        else
        {
            // Validate the Anti-XSRF token
            if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
            {
                throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
    {
        Context.GetOwinContext().Authentication.SignOut();
    }
}

}

Это мой пользовательский элемент управления для всплывающего окна:

    <div class="modal fade pop-up-1" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel-1" aria-hidden="true">
            <div class="modal-dialog modal-lg">
              <div class="modal-content">
                <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                  <h4 class="modal-title" id="myLargeModalLabel-3">Contact Us</h4>
                </div>
                <div class="modal-body">
                <table style="max-width:100%; height: auto; padding:20px">
                    <tr>
                        <td colspan="3">
                            <div style="margin:15px 0 20px 0"> Please, use the form below to contact us regarding any questions or concerns you might have:</div>
                        </td>
                    </tr>
                    <tr style="margin-bottom:10px">
                        <td style="width:150px; font-size:14px">Name:</td>
                        <td style="vertical-align:top; width:300px">
                            <asp:TextBox ID="txtName" runat="server" Width="300px" style="margin:10px"/>
                        </td>
                        <td>
                            <!--<asp:RequiredFieldValidator ID="rfvName" runat="server"
                                ControlToValidate="txtName" Display="Dynamic"
                                ErrorMessage="Name">*</asp:RequiredFieldValidator>-->
                        </td>
                    </tr>
                    <tr style="margin-bottom: 10px ">
                        <td style="font-size: 14px">Organization (optional):</td>
                        <td><asp:TextBox ID="txtOrganization" runat="server" Width="300px" style="margin:10px" /></td>
                        <td>
                        </td>
                    </tr>
                    <tr style="margin-bottom:10px">
                        <td style="font-size:14px"> Phone (optional):</td>
                        <td><asp:TextBox ID="txtPhone" runat="server" Width="300px" style="margin:10px" /></td>
                        <td>
                        </td>
                    </tr>
                    <tr style="margin-bottom:10px">
                        <td style="font-size:14px">Email:</td>
                        <td><asp:TextBox ID="txtEmail" runat="server" Width="300px" style="margin:10px" /></td>
                        <td>
                            <!--<asp:RequiredFieldValidator ID="rfvEmail" runat="server"
                                ControlToValidate="txtEmail" Display="Dynamic"
                                ErrorMessage="Email">*</asp:RequiredFieldValidator>-->
                        </td>
                    </tr>
                    <tr>
                        <td style="font-size:14px"> Message:</td>
                        <td><asp:TextBox ID="txtRequest" runat="server" TextMode="MultiLine" Width="300px" Height="60px" style="margin:10px" /></td>
                        <td>
                            <!--<asp:RequiredFieldValidator ID="rfvRequest" runat="server"
                                ControlToValidate="txtRequest" Display="Dynamic"
                                ErrorMessage="Message">*</asp:RequiredFieldValidator>-->
                        </td>
                    </tr>
                    <tr>
                        <td colspan="3">
                            <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="SendMail" Width="60px" />&nbsp;
                            <asp:Button ID="btnReset" runat="server" Text="Reset" OnClick="ResetEmail" Width="60px" CausesValidation="false" />
                                <!--<asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Please fill out the required fields:" ShowMessageBox="true" ShowSummary="false" />-->
                        </td>
                    </tr>
                </table>
                </div>
              </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
          </div><!-- /.modal Contact Table-->

И, наконец, что не менее важно, это код в пользовательском элементе управления, и да, я знаю, что могу сделать это и с помощью своего web.config, и я тоже попробовал это с тем же результатом:

     public partial class pop_up_1 : System.Web.UI.UserControl
{
    private bool IsValid;

    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void SendMail(object sender, EventArgs e)
    {
        if (IsValid)
        {
            //create a new email message
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("");
            mail.To.Add("");
            mail.Subject = "Information Request";
            mail.IsBodyHtml = true;
            mail.Body = "Name:" + this.txtName.Text + "<br />";
            mail.Body += "Organization:" + txtOrganization.Text + "<br />";
            mail.Body += "Phone:" + txtPhone.Text + "<br />";
            mail.Body += "Email:" + txtEmail.Text + "<br />";
            mail.Body += "Request or Question:" + txtRequest.Text + "<br />";


            //Create SMTP client
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "";


            //Send the email
            smtp.Send(mail);

            //Define the name and type of the client script on the page.
            String csName = "SuccessNotificationScript";
            Type csType = this.GetType();

            //Get a ClientScriptManager reference from the Page class.
            ClientScriptManager cs = Page.ClientScript;

            //Check to see if the client script is already registered.
            if (!cs.IsClientScriptBlockRegistered(csType, csName))
            {
                string csText = "<script language='javascript'>window.alert('Thank you for submitting your request');</script>";
                cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
            }
            //Clear the form
            ClearForm();
        }
    }
    protected void ResetEmail(object sender, EventArgs e)
    {
        ClearForm();
    }

    protected void ClearForm()
    {
        txtName.Text = "";
        txtOrganization.Text = "";
        txtPhone.Text = "";
        txtEmail.Text = "";
        txtRequest.Text = "";
    }
}

}

Любые предложения или идеи, с благодарностью. Спасибо

вот серверная часть моей страницы входа, я использую платформу идентификации:

     public partial class Login : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //RegisterHyperLink.NavigateUrl = "Register";
        // Enable this once you have account confirmation enabled for password reset functionality
        // ForgotPasswordHyperLink.NavigateUrl = "Forgot";
        //OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
        var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
        if (!String.IsNullOrEmpty(returnUrl))
        {
            //RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
        }
    }

    protected void LogIn(object sender, EventArgs e)
    {
        if (IsValid)
        {
            // Validate the user password
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            ApplicationUser user = manager.Find(Email.Text, Password.Text);
            if (user != null)
            {
                IdentityHelper.SignIn(manager, user, RememberMe.Checked);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else
            {
                FailureText.Text = "Invalid username or password.";
                ErrorMessage.Visible = true;
            }
        }
    }
}

}

0 ответов

Другие вопросы по тегам