Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 发送HTTP标头后,服务器无法修改Cookie,如何修复?_C#_Asp.net_Cookies_Forms Authentication - Fatal编程技术网

C# 发送HTTP标头后,服务器无法修改Cookie,如何修复?

C# 发送HTTP标头后,服务器无法修改Cookie,如何修复?,c#,asp.net,cookies,forms-authentication,C#,Asp.net,Cookies,Forms Authentication,如果Cookie中存在用户名和密码,我想在母版页加载页面自动登录我的用户 所以我写了下面的代码: protected void Page_Load(object sender, EventArgs e) { LoadDataFromCookieIfExistAndLogin(); } private void LoadDataFromCookieIfExistAndLogin() { string Query =

如果Cookie中存在用户名和密码,我想在母版页加载页面自动登录我的用户
所以我写了下面的代码:

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadDataFromCookieIfExistAndLogin();
        }

private void LoadDataFromCookieIfExistAndLogin()
{
    string Query = Request.Url.Query.ToString();
    string[] Ar_Query = new string[2];
    string[] splitter = { "%2f" };
    Ar_Query = Query.Split(splitter, System.StringSplitOptions.None);
    string[] Ar_new_Query = new string[2];
    int minLength = Math.Min(Ar_Query.Length, Ar_new_Query.Length);
    Array.Copy(Ar_Query, Ar_new_Query, minLength);
    if (string.IsNullOrEmpty(Ar_new_Query[1]))
    {
        Ar_new_Query[1] = string.Empty;
    }

    if ((Request.QueryString["ReturnURL"] != null) && (Ar_new_Query[1].ToString().ToUpper() == "ADMIN"))
    {
        Session.Clear();
        FormsAuthentication.SignOut();
    }
    else if ((Request.QueryString["ReturnURL"] != null) && (Ar_new_Query[1].ToString().ToUpper() == "ELMAH.AXD"))
    {
        Session.Clear();
        FormsAuthentication.SignOut();
    }
    else
    {
        HttpCookie Situation_Cookie = Request.Cookies["Situation"];
        if (Situation_Cookie != null)
        {
            if (Situation_Cookie["Login"] == "Yes")
            {
                HttpCookie Data_Cookie = Request.Cookies["Data"];
                if (Data_Cookie != null)
                {
                    string UserName = Data_Cookie["UserName"].ToString();
                    string PassWord = ata_Cookie["PassWord"].ToString();

                    string HashedPass = FormsAuthentication.HashPasswordForStoringInConfigFile(PassWord, "MD5");
                    DataSet dsUsers = DataLayer.Users.SelectRowForLogin_FromCookie(UserName, HashedPass);
                    if (dsUsers.Tables["Users"].Rows.Count > 0)
                    {
                        DataRow drUsers = dsUsers.Tables["Users"].Rows[0];

                        if (Session["User_ID"] == null)
                        {
                            Session["UserName"] = UserName;
                            Session["Password"] = PassWord;
                            Session["User_ID"] = drUsers["ID"].ToString();
                            Session["UserType_ID"] = drUsers["UserType_ID"].ToString();
                            DataLayer.OnlineUsers.UpdateRow_UserID_By_SessionID(
                                                                                 Session["User_ID"],
                                                                                 Session.SessionID);
                        }
                        if (!HttpContext.Current.User.Identity.IsAuthenticated)
                        {
                            FormsAuthentication.SetAuthCookie(drUsers["ID"].ToString(), true);
                        }
                    }
                }
            }
        }
    }
}
为了理解我的登录代码,我使用RoleProvider,如下所示:

  using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Data;

    namespace NiceFileExplorer.Classes
    {
        public class NiceFileExplorerRoleProvider : RoleProvider
        {
            public override void AddUsersToRoles(string[] usernames, string[] roleNames)
            {
                throw new NotImplementedException();
            }

            public override string ApplicationName
            {
                get
                {
                    throw new NotImplementedException();
                }
                set
                {
                    throw new NotImplementedException();
                }
            }

            public override void CreateRole(string roleName)
            {
                throw new NotImplementedException();
            }

            public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
            {
                throw new NotImplementedException();
            }

            public override string[] FindUsersInRole(string roleName, string usernameToMatch)
            {
                throw new NotImplementedException();
            }

            public override string[] GetAllRoles()
            {
                throw new NotImplementedException();
            }

            //public override string[] GetRolesForUser(string username)
            public override string[] GetRolesForUser(string User_ID)
            {
                string[] UserTypes = new string[1];
                DataSet dsUser = DataLayer.Users.SelectRowWithUserTypeInfo(int.Parse(User_ID));
                if (dsUser.Tables["Users"].Rows.Count > 0)
                {
                    DataRow drUser = dsUser.Tables["Users"].Rows[0];
                    UserTypes[0] = drUser["Name"].ToString();
                }
                if (User_ID == "-255")
                {
                    UserTypes[0] = "Administrators";
                }
                return UserTypes;
            }

            public override string[] GetUsersInRole(string roleName)
            {
                throw new NotImplementedException();
            }

            public override bool IsUserInRole(string username, string roleName)
            {
                throw new NotImplementedException();
            }

            public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
            {
                throw new NotImplementedException();
            }

            public override bool RoleExists(string roleName)
            {
                throw new NotImplementedException();
            }
        }

}
有时我会出现以下错误:

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadDataFromCookieIfExistAndLogin();
        }

private void LoadDataFromCookieIfExistAndLogin()
{
    string Query = Request.Url.Query.ToString();
    string[] Ar_Query = new string[2];
    string[] splitter = { "%2f" };
    Ar_Query = Query.Split(splitter, System.StringSplitOptions.None);
    string[] Ar_new_Query = new string[2];
    int minLength = Math.Min(Ar_Query.Length, Ar_new_Query.Length);
    Array.Copy(Ar_Query, Ar_new_Query, minLength);
    if (string.IsNullOrEmpty(Ar_new_Query[1]))
    {
        Ar_new_Query[1] = string.Empty;
    }

    if ((Request.QueryString["ReturnURL"] != null) && (Ar_new_Query[1].ToString().ToUpper() == "ADMIN"))
    {
        Session.Clear();
        FormsAuthentication.SignOut();
    }
    else if ((Request.QueryString["ReturnURL"] != null) && (Ar_new_Query[1].ToString().ToUpper() == "ELMAH.AXD"))
    {
        Session.Clear();
        FormsAuthentication.SignOut();
    }
    else
    {
        HttpCookie Situation_Cookie = Request.Cookies["Situation"];
        if (Situation_Cookie != null)
        {
            if (Situation_Cookie["Login"] == "Yes")
            {
                HttpCookie Data_Cookie = Request.Cookies["Data"];
                if (Data_Cookie != null)
                {
                    string UserName = Data_Cookie["UserName"].ToString();
                    string PassWord = ata_Cookie["PassWord"].ToString();

                    string HashedPass = FormsAuthentication.HashPasswordForStoringInConfigFile(PassWord, "MD5");
                    DataSet dsUsers = DataLayer.Users.SelectRowForLogin_FromCookie(UserName, HashedPass);
                    if (dsUsers.Tables["Users"].Rows.Count > 0)
                    {
                        DataRow drUsers = dsUsers.Tables["Users"].Rows[0];

                        if (Session["User_ID"] == null)
                        {
                            Session["UserName"] = UserName;
                            Session["Password"] = PassWord;
                            Session["User_ID"] = drUsers["ID"].ToString();
                            Session["UserType_ID"] = drUsers["UserType_ID"].ToString();
                            DataLayer.OnlineUsers.UpdateRow_UserID_By_SessionID(
                                                                                 Session["User_ID"],
                                                                                 Session.SessionID);
                        }
                        if (!HttpContext.Current.User.Identity.IsAuthenticated)
                        {
                            FormsAuthentication.SetAuthCookie(drUsers["ID"].ToString(), true);
                        }
                    }
                }
            }
        }
    }
}
System.Web.HttpException:发送HTTP头后,服务器无法修改cookie。

System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.Web.HttpException (0x80004005): Server cannot modify cookies after HTTP headers have been sent.
   at System.Web.HttpCookieCollection.Add(HttpCookie cookie)
   at System.Web.Security.FormsAuthentication.SetAuthCookie(String userName, Boolean createPersistentCookie, String strCookiePath)
   at NiceFileExplorer.en.Site1.Page_Load(Object sender, EventArgs e)
   at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
   at System.Web.UI.Page.HandleError(Exception e)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
   at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
   at System.Web.UI.Page.ProcessRequest()
   at System.Web.UI.Page.ProcessRequest(HttpContext context)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
问题似乎出在下面这行:

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadDataFromCookieIfExistAndLogin();
        }

private void LoadDataFromCookieIfExistAndLogin()
{
    string Query = Request.Url.Query.ToString();
    string[] Ar_Query = new string[2];
    string[] splitter = { "%2f" };
    Ar_Query = Query.Split(splitter, System.StringSplitOptions.None);
    string[] Ar_new_Query = new string[2];
    int minLength = Math.Min(Ar_Query.Length, Ar_new_Query.Length);
    Array.Copy(Ar_Query, Ar_new_Query, minLength);
    if (string.IsNullOrEmpty(Ar_new_Query[1]))
    {
        Ar_new_Query[1] = string.Empty;
    }

    if ((Request.QueryString["ReturnURL"] != null) && (Ar_new_Query[1].ToString().ToUpper() == "ADMIN"))
    {
        Session.Clear();
        FormsAuthentication.SignOut();
    }
    else if ((Request.QueryString["ReturnURL"] != null) && (Ar_new_Query[1].ToString().ToUpper() == "ELMAH.AXD"))
    {
        Session.Clear();
        FormsAuthentication.SignOut();
    }
    else
    {
        HttpCookie Situation_Cookie = Request.Cookies["Situation"];
        if (Situation_Cookie != null)
        {
            if (Situation_Cookie["Login"] == "Yes")
            {
                HttpCookie Data_Cookie = Request.Cookies["Data"];
                if (Data_Cookie != null)
                {
                    string UserName = Data_Cookie["UserName"].ToString();
                    string PassWord = ata_Cookie["PassWord"].ToString();

                    string HashedPass = FormsAuthentication.HashPasswordForStoringInConfigFile(PassWord, "MD5");
                    DataSet dsUsers = DataLayer.Users.SelectRowForLogin_FromCookie(UserName, HashedPass);
                    if (dsUsers.Tables["Users"].Rows.Count > 0)
                    {
                        DataRow drUsers = dsUsers.Tables["Users"].Rows[0];

                        if (Session["User_ID"] == null)
                        {
                            Session["UserName"] = UserName;
                            Session["Password"] = PassWord;
                            Session["User_ID"] = drUsers["ID"].ToString();
                            Session["UserType_ID"] = drUsers["UserType_ID"].ToString();
                            DataLayer.OnlineUsers.UpdateRow_UserID_By_SessionID(
                                                                                 Session["User_ID"],
                                                                                 Session.SessionID);
                        }
                        if (!HttpContext.Current.User.Identity.IsAuthenticated)
                        {
                            FormsAuthentication.SetAuthCookie(drUsers["ID"].ToString(), true);
                        }
                    }
                }
            }
        }
    }
}
FormsAuthentication.SetAuthCookie(Druser[“ID”].ToString(),true)


这个错误是什么意思?我如何防止它

如果您使用ASP.Net标准表单身份验证,则如果您使用持久cookie,则此功能可用于表单身份验证。见MSDN文章。检查文档的“创建表单验证Cookie”部分

您不需要保留用户名\密码组合为cookie。这不是一个好的做法,因为任何人都可以从cookie中嗅出这个用户名\密码。我强烈建议您阅读上述文章,了解表单身份验证的工作原理。

“System.Web.HttpException:发送HTTP头后,服务器无法修改Cookie。”

该错误表示您正在尝试在http响应完成后修改Cookie

我认为问题在于您试图在执行后修改cookies FormsAuthentication.SignOut()

根据MSDN,调用SignOut()方法时会发生这种情况

调用SignOut方法时,通过调用redirect方法将endResponse参数设置为false,从而重定向到应用程序的登录页面。在当前页面完成执行之前,不会发生重定向,因此可以运行其他代码。如果代码不包含指向其他页面的显式重定向,则会将用户重定向到应用程序配置文件中配置的登录页面


因此,您正在尝试在重定向发生后修改cookie。您可以通过在重定向之前设置cookie值来避免此错误。

对于快速测试,我已经清除了浏览器历史记录,并且在我的端运行良好。

感谢您的回答/但正如您所看到的,我的方法中没有注销或重定向(LoadDataFromCookieIfExistAndLogin())。那么,为什么仍然存在该错误->只有elmah显示此错误,visual studio在调试期间显示此错误。在浏览器中处理页面时不会显示此错误!我是指FormsAuthentication.SignOut();请确保FormsAuthentication.SignOut();在修改/设置cookie值之前不执行->没有FormsAuthentication.SignOut();在修改/设置cookie值之前,这正是我想知道的,为什么我有异常?哪个顺序正确?1)
FormsAuthentication.SignOut()
2)
Session.放弃()
3)
var cookie=new-HttpCookie(FormsAuthentication.formscookeName,”;cookie.Expires=DateTime.Now.AddYears(-1);Response.Cookies.Add(cookie)原因可能是用户已通过身份验证且其表单身份验证cookie已设置。尝试将用户ID放入一个新的Cookie中这实际上不会修复该异常,除非您正在做一些非常奇怪的事情,在这种情况下,它会返回。Session.Clear()或Session.about()?