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

标签 c# asp.net forms-authentication

在我的网站上,我正在使用表单例份验证。我想为此目的发出网络请求,我正在寻求 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/

相关文章:

c# - DLL 函数调用不起作用

c# - 静电会使它变慢吗

javascript - 尝试从 C# 中的文本框获取文本值时出错(ASP.NET gridview)

asp.net - 如何将 Unicode 值作为 select 命令的参数传递

asp.net-mvc - ASP.Net MVC 应用程序注销未完全注销

sharepoint-2010 - SharePoint 2010 自定义 WCF 服务 - Windows 和 FBA 身份验证

asp.net-mvc - 如果经过身份验证,MVC 中的默认页面会有所不同

c# - 通过 C# 执行 WinDbg 命令

c# - 计算每个 x 和 y 坐标的距离

c# - Repeater 内的 Linkbutton 用于分页 ASP.Net