在我的网站上,我正在使用表单身份验证。我想为此目的进行网络请求,我正在接受 cookieContainer 的帮助。我的代码是这个
string url = HttpContext.Current.Request.Url.AbsoluteUri;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
Cookie authenticationCookie = new Cookie(
FormsAuthentication.FormsCookieName,
cookie.Value,
cookie.Path,
HttpContext.Current.Request.Url.Authority);
req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(authenticationCookie);
WebResponse res = req.GetResponse();
但是此代码抛出错误“ Cookie的'Domain'='localhost:300'部分无效。”。因此我发现错误来自这行代码
Cookie authenticationCookie = new Cookie(
FormsAuthentication.FormsCookieName,
cookie.Value,
cookie.Path,
HttpContext.Current.Request.Url.Authority);
该网站的网址是localhost:300。我无法找到任何解决方案。任何人都告诉我出了什么问题?
答案 0 :(得分:5)
尝试从您传递给Cookie构造函数的域属性中排除端口号:
Cookie authenticationCookie = new Cookie(
FormsAuthentication.FormsCookieName,
cookie.Value,
cookie.Path,
HttpContext.Current.Request.Url.Host
);
或直接将cookie设置为HTTP标头,而不使用cookie容器:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
req.Headers[HttpRequestHeader.Cookie] = string.Format("{0}={1}", cookie.Name, cookie.Value);
WebResponse res = req.GetResponse();