Created
January 30, 2012 01:25
-
-
Save danmiser/1701803 to your computer and use it in GitHub Desktop.
ASP.NET MVC FormsAuthentication with ServiceStack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Client code follows... | |
CookieContainer cookieContainer = new CookierContainer(); | |
if (Login("user", "password")) | |
{ | |
// Now we can use the ServiceStack classes to call the /api section | |
var client = new JsonServiceClient("http://localhost:8080/api"); | |
client.CookieContainer = cookieContainer; | |
var request = new Sync {LastSync = DateTime.Now}; | |
var response = client.Send<Sync>(request); | |
} | |
private static bool Login(string username, string password) | |
{ | |
var client = (HttpWebRequest) WebRequest.Create("http://localhost:8080/Account/Logon"); | |
client.Method = "POST"; | |
client.UserAgent = "ServiceStack"; | |
client.ContentType = "application/x-www-form-urlencoded"; | |
client.CookieContainer = cookieContainer; | |
string poststring = "username=" + username + "&password=" + password; | |
byte[] bytedata = Encoding.UTF8.GetBytes(poststring); | |
client.ContentLength = bytedata.Length; | |
using (var requestStream = client.GetRequestStream()) | |
{ | |
requestStream.Write(bytedata, 0, bytedata.Length); | |
} | |
using (var response = client.GetResponse()) | |
{ | |
using (var responseStream = response.GetResponseStream()) | |
{ | |
using (StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8)) | |
{ | |
string s = reader.ReadToEnd(); | |
// When running under MonoTouch, the Cookies were coming back with $Version=1 | |
// which would break when sending the CookieContainer back to the server for the next call | |
foreach (Cookie c in cookieContainer.GetCookies(new Uri("http://localhost:8080"))) | |
{ | |
c.Version = 0; | |
} | |
return !s.Contains("The user name or password provided is incorrect"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment