我成功登录到MVC 4 Web API站点并获得了 . ASPXAUTH以这种方式设置 Cookie:
private void Login()
{
var client = new RestClient("http://QQQQ/MobileAPI");
client.CookieContainer = new CookieContainer();
var request = new RestRequest {Resource = "/api/account/Logon", Method = Method.POST};
request.AddObject(new {Username = "john", Password = "secret"});
var responseLogin = client.Execute(request);
if (responseLogin.StatusCode == HttpStatusCode.OK)
ProcessData(client.CookieContainer);
}
如您所见,我将CookieContainer 传递给ProcessData()
函数,然后处理位于控制器后面的RESTful命令。[AUTHORIZE]
ProcessData() 调用失败并显示 HttpStatusCode.Unauthorized
问题:我假设我没有正确发送身份验证?
private void ProcessData(CookieContainer cookieJar)
{
var client = new RestClient("QQQQQ/MobileAPI");
client.CookieContainer = cookieJar;
var request = new RestRequest {Resource = "/api/values/5", Method = Method.GET};
var responseForUser = client.ExecuteAsGet<AppUser>(request, "GET");
if (responseForUser.StatusCode == HttpStatusCode.OK)
{
AppUser app = responseForUser.Data;
Console.WriteLine(app.CUSAName);
}
if (responseForUser.StatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("FAILED");
}
}