Recently at work I needed to create a WPF application to read in data from an excel file and post it to a page on our production site. This requires a login from a user with prod access. Since our website uses cookie authentication, this app therefore needed to pass the authentication and session cookies with each request.
This is a quick recipe for how to do that in a WPF desktop app which makes calls via HttpClient.
Assuming you have created a simple WPF application with a single "MainWindow.xaml.cs" file. In that file, add member variables to store the cookies, plus a few constants for later use:
const string ASPXAUTH_Cookie = ".ASPXAUTH";
const string ASPNET_SessionId_Cookie = "ASP.NET_SessionId";
IEnumerable<Cookie> _responseCookies;
In the function which makes the HttpClient Post Call for login page (full details not shown), add the following after the PostAsync call:
var postResult = await client.PostAsync(url, content);
if (postResult.StatusCode == HttpStatusCode.OK)
{
// Get the cookies
Uri uri = new Uri(url);
_responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
// See if authentication and session cookies were returned:
if (_responseCookies.Any(c => c.Name == ASPXAUTH_Cookie) &&
_responseCookies.Any(c => c.Name == ASPNET_SessionId_Cookie))
{
_isLoggedIn = true;
}
}
After a successful login, the _responseCookies now hold the proper cookie values.
Now create a function which will be called for all methods which will be making follow-up calls to the website. This will create an HttpClient instance which is configured to send the stored cookies:
public HttpClient createHttpClientWithCookies()
{
var cookieContainer = new CookieContainer();
if (_responseCookies != null)
{
foreach (var cookie in _responseCookies)
{
if (cookie.Name == ASPXAUTH_Cookie ||
cookie.Name == ASPNET_SessionId_Cookie)
{
cookieContainer.Add(cookie);
}
}
}
var handler = new HttpClientHandler() { CookieContainer = cookieContainer };
HttpClient client = new HttpClient(handler);
return client;
}
Now all subsequent HTTP calls will simply look similar to this:
using (HttpClient client = createHttpClientWithCookies())
{
var getResult = await client.GetAsync(url);
if (getResult.StatusCode == HttpStatusCode.OK)
{
// TODO
}
}
Now the HttpClient in this call will ensure the authentication and session cookies get passed along with the request. That's really all there is to it.