Reputation: 79
To workaround the "Cookies Disabled" issue, I use CookieContainer myContainer = new CookieContainer(); request.CookieContainer = myContainer; This works when the getIDfromWeb function is first called. However, when the getIDfromWeb function is called again, "Cookies disabled" occurs. How should I workaround this issue? To reproduce the same issue, you need to meet the "Cookies Disabled" issue when you do not include "request.CookieContainer = myContainer;" otherwise your url may not need authentication. Although I can get the information by placing my URL on the IE address bar and hitting enter, I met authorization error when implementing this from C#. I use httpwebrequest and cookies to workaround issue but found I met "Cookies disabled" issue when I called the function the second time.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
const string baseURL = "http://intranet/rest/reserveid.php";
static void Main(string[] args)
{
Console.WriteLine("Key1 sample:");
Console.WriteLine(getIDfromWeb("key1"));
Console.WriteLine("key1. sample2:");
Console.WriteLine(getIDfromWeb("key1"));
Console.ReadKey();
}
static string getIDfromWeb(string idType)
{
int startPos = 0;
string url = "";
switch (idType)
{
case "key1":
startPos = 19;
url = baseURL + "?querystringforkey1";
break;
case "key2":
startPos = 15;
url = baseURL + "?querystringforkey2";
break;
}
CookieContainer myContainer = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = CredentialCache.DefaultNetworkCredentials;
request.CookieContainer = myContainer;
request.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
reader.Close();
response.Close();
return responseFromServer.Substring(startPos, (responseFromServer.IndexOf("}]") - startPos - 1));
}
}
}
Upvotes: 0
Views: 35
Reputation: 151
Its work for me.
Here is Updated your code, Please check.
static void Main(string[] args)
{
Console.WriteLine("Key1 sample:");
Console.WriteLine(getIDfromWeb("key1"));
Console.WriteLine("key1. sample2:");
Console.WriteLine(getIDfromWeb("key2"));
Console.ReadKey();
}
Replace below line
Console.WriteLine(getIDfromWeb("key2"));
Upvotes: 1