2

在我的网站中,我正在使用表单身份验证。我想为此目的进行网络请求,我正在使用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。我找不到任何解决方案。谁能告诉我出了什么问题?

4

1 回答 1

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();
于 2013-01-14T13:37:21.023 回答