通过添加cookie来验证webrequest会抛出错误

本文关键字:出错 错误 webrequest 验证 添加 cookie | 更新日期: 2023-09-27 17:52:47

在我的网站我使用表单认证。我想为此目的做一个webrequest,我正在帮助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);

站点的url是localhost:300。我找不到任何解决办法。谁能告诉我哪里出错了?

通过添加cookie来验证webrequest会抛出错误

尝试从传递给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();
相关文章: