I am new at c#, when I call api to a uri, it asks me to store cookies after logging in at the login uri. I have stored it by using static variable. But still can't login. It still shows the error:
Session Login is expired, you must login again, when i print out cookies, same cookie at 2 request, login uri, eg: JSESSION: 512F582H395D465BAFDF63B0D5D21C16.
Anyone can check for me? Thank you.
static Uri uri = new Uri("http://myurl.com/login"); //example uri
static Uri uri1 = new Uri("http://myurl.com/listMap");
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
await Login_ClickAsync();
foreach (Cookie cookie in cookieContainer.GetCookies(uri))
{
Console.WriteLine("Cookie0:" + cookie.ToString());
}
}
static CookieContainer cookieContainer = new CookieContainer();
static HttpClientHandler httpClientHandler = new HttpClientHandler
{
CookieContainer = cookieContainer
};
static HttpClient client = new HttpClient(httpClientHandler);
static async Task Login_ClickAsync()
{
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var keyValues = new List<KeyValuePair<string, string>>();
// add API method parameters
keyValues.Add(new KeyValuePair<string, string>("userName", "testaccount"));
keyValues.Add(new KeyValuePair<string, string>("password", "123456"));
HttpContent multiForm = new FormUrlEncodedContent(keyValues);
//request.ContentType = "application/x-www-form-urlencoded";
HttpResponseMessage resposne = await client.PostAsync(uri, multiForm);
//CookieContainer _cookieContainer =
cookieContainer = GetCookies(resposne); ;
if (resposne.IsSuccessStatusCode)
{
foreach (Cookie cookie in cookieContainer.GetCookies(uri))
{
Console.WriteLine("Cookie1:" + cookie.ToString());
}
await getData();
}
else
{
Console.WriteLine("False");
}
}
public static CookieContainer GetCookies(HttpResponseMessage response)
{
var pageUri = response.RequestMessage.RequestUri;
var _cookieContainer = new CookieContainer();
IEnumerable<Cookie> responseCookies = cookieContainer.GetCookies(uri).Cast<Cookie>();
foreach (Cookie c in responseCookies)
{
Console.WriteLine("Coookie111:" + c);
_cookieContainer.Add(pageUri, c);
}
return _cookieContainer;
}
static async Task getData()
{
var keyValues = new List<KeyValuePair<string, string>>();
HttpContent multiForm = new FormUrlEncodedContent(keyValues);
HttpResponseMessage resposne = await client.PostAsync(uri1, multiForm);
if (resposne.IsSuccessStatusCode)
{
string response1 = await resposne.Content.ReadAsStringAsync();
Console.WriteLine(response1.ToString());
foreach (Cookie cookie in cookieContainer.GetCookies(uri1))
{
Console.WriteLine("Cookie2:" + cookie);
}
}
else
{
Console.WriteLine("False");
}
}
}```