C# 通过添加Cookie验证webrequest会引发错误
在我的网站中,我使用表单身份验证。为此,我想提出一个webrequest,我需要cookieContainer的帮助。我的代码是C# 通过添加Cookie验证webrequest会引发错误,c#,asp.net,forms-authentication,C#,Asp.net,Forms Authentication,在我的网站中,我使用表单身份验证。为此,我想提出一个webrequest,我需要cookieContainer的帮助。我的代码是 string url = HttpContext.Current.Request.Url.AbsoluteUri; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); HttpCookie cookie = HttpContext.Current.Request.Cookies[F
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);
该站点的url为localhost:300。我找不到任何解决方案。有人能告诉我出了什么问题吗?尝试从传递给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();
我不知道为什么,但当代码执行到达这一行“WebResponse res=req.GetResponse();”时,它将返回到第一行(HttpWebRequest req=(HttpWebRequest)WebRequest.Create(url);),因为它处于循环中。最后抛出一个错误“请求被中止:操作已超时”。我不知道为什么会发生这种情况。也许你有多个线程。从您显示的代码很难判断。也许问题出在服务器端。既然您已成功通过身份验证,那么服务器上肯定还有其他问题。通过以下步骤,您可以激活网络跟踪并准确查看通过网络发送的内容:。或者简单地用一个像Fiddler这样的工具来看看盖子下面发生了什么。