我正在尝试发送请求到我的MVC3应用程序,我已经尝试了常规的WebRequest,我正在尝试使用RestSharp应用正确的验证器,但它仍然返回登录页面的重定向结果?
我做错了什么?
更新:我应该如何使用RestSharp进行表单身份验证?我想这是有可能的-只需要玩玩那块饼干...
发布于 2012-10-23 20:12:31
如果要重定向到登录页面,则必须为表单身份验证设置MVC3应用程序。窗体身份验证将需要随请求一起发送cookie。如果您在RestSharp中使用基本身份验证器,这将不起作用。我假设您正在使用MVC控制器来提供您正在尝试调用的REST API。
一种选择是升级到MVC4并使用HTTP来开发您的REST API。在ASP.NET Web中,授权行为略有不同,它将返回HTTP401错误,而不是执行重定向。您还可以定制AuthorizationAttribute,将信息从header中提取出来,以进行基本身份验证和授权。
另一种选择是,如果控制器上的操作不需要身份验证/授权,则可以将AllowAnonymousAttribute放在该方法上。
发布于 2012-10-24 17:17:40
要通过表单身份验证,您必须获取cookie并将其粘贴到RestSharp的cookie容器中。要获取cookie,只需使用常规WebRequest即可。
private Cookie GetAuthCookie(string user, string pass)
{
var http = WebRequest.Create(_baseUrl+"Users/Login") as HttpWebRequest;
http.AllowAutoRedirect = false;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
http.CookieContainer = new CookieContainer();
var postData = "UserName=" + user + "&Password=" + pass + "&RememberMe=true&RememberMe=false&ReturnUrl=www.google.com";
byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (var postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
var httpResponse = http.GetResponse() as HttpWebResponse;
return httpResponse.Cookies[FormsAuthentication.FormsCookieName];
}
https://stackoverflow.com/questions/13037072
复制