I have a controller / action in an ASP.NET MVC3 app. It handles the post request for a user login. I am trying to simulate that but from a desktop winForms app.
My controller looks like this:
[HttpPost]
[AllowAnonymous]
public virtual ActionResult LogOn(LogOnModel model, string returnUrl)
{
//authenticate user logic
}
I’m generating my HTTP request this way:
public static bool AuthenticateClient(Client client, string username, string password)
{
// change these field names to whatever elements your login page is expecting
string usernameField = username;
string passwordField = password;
string loginUrl = "http://localhost/Account/LogOn/";
// format login request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(loginUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
request.CookieContainer = new CookieContainer();
// format and send login data
string requestData = JSON.Serialize(new LogOnModel(usernameField, passwordField, false));
StreamWriter sw = new StreamWriter(request.GetRequestStream());
sw.Write(requestData);
sw.Close();
// get the login response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string responseData = sr.ReadToEnd();
sr.Close();
// retrieve the session ID
string sessionId = null;
foreach (Cookie cookie in response.Cookies)
{
if (cookie.Name == AuthCookieName)
{
sessionId = cookie.Value;
}
}
// could not authenticate
if (sessionId == null)
{
return false;
}
// send the session ID with every request
client.OnRequestCreated = (args) =>
{
args.Request.Headers["Cookie"] = string.Format("{0}={1}", AuthCookieName, sessionId);
};
return true;
}
Typically, I can make Ajax requests from jQuery and pass it the same object parameters that the Controller Action is expecting (the LogonModel in this case), however, when I do that from my desktop app, it’s showing up as null for me each time in the action.
So my question is, how can I make the request from my desktop winforms app, and fill the object (LogonModel) in the controller so that I can authenticate?
(For completeness…)
You can never be too sure whether you are framing the request right. Personally I’ve found it easier to monitor and compare the calls using Fiddler then refine and emulate as necessary…