gpt4 book ai didi

c# - 通过添加 Cookie 验证 Web 请求会抛出错误

转载 作者:行者123 更新时间:2023-12-02 22:16:52 24 4
gpt4 key购买 nike

在我的网站上,我正在使用表单例份验证。我想为此目的发出网络请求,我正在寻求 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 构造函数的域属性中排除端口号:

Cookie authenticationCookie = new Cookie(
FormsAuthentication.FormsCookieName,
cookie.Value,
cookie.Path,
HttpContext.Current.Request.Url.Host
);

或者不使用 cookie 容器直接将 cookie 设置为 HTTP header :

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();

关于c# - 通过添加 Cookie 验证 Web 请求会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14319178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com