None
None

Reputation: 5670

Authenticating a webrequest by adding Cookies throws error

In my website I am using forms authentication.And I want to make a webrequest for this purpose i am taking help of cookieContainer.My code is this

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

but this code throws an error "The 'Domain'='localhost:300' part of the cookie is invalid.".Thus i found error is coming from this line of code

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

The url of the site is localhost:300. I am unable to find any solution for this.can any one tell me what went wrong?

Upvotes: 2

Views: 2319

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

Try excluding the port number from the domain property you are passing to the Cookie constructor:

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

or set the cookie as an HTTP header directly without using a cookie container:

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

Upvotes: 5

Related Questions