1

我正在尝试向我的 MVC3 应用程序发送请求,我已经尝试过常规 WebRequest,我正在尝试使用 RestSharp 应用正确的 Authenticator,但它仍然返回登录页面的重定向结果?

我究竟做错了什么?

upd:我应该如何使用 RestSharp 进行表单身份验证?我想这是有可能的——只需要玩弄那个饼干......

4

2 回答 2

1

如果您被重定向到登录页面,则必须设置您的 mvc 3 应用程序以进行表单身份验证。表单身份验证将需要与请求一起发送的 cookie。如果您在 RestSharp 中使用基本身份验证器,这将不起作用。我假设您正在使用 MVC 控制器来提供您尝试调用的 REST API。

一种选择是升级到 MVC 4 并使用 ASP.NET Web API 来开发您的 REST API。授权行为在 ASP.NET Web API 中略有不同,因为它将返回 HTTP 401 错误而不是执行重定向。并且您可以自定义 AuthorizationAttribute 以从 HTTP 标头中提取信息以进行基本身份验证和授权。

另一种选择是,如果控制器上的操作不需要身份验证/授权,您可以将 AllowAnonymousAttribute 放在该方法上。

于 2012-10-23T20:12:31.153 回答
0

要通过 Forms 身份验证,您必须获取 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];
    }
于 2012-10-24T17:17:39.707 回答