获取auth cookie的ASP MVC + HttpWebRequest应用程序,我如何强制它工作?

时间:2012-10-09 19:35:41

标签: c# asp.net-mvc httpwebrequest

本帖末尾的最后更新

我正在整天工作,我无法让它发挥作用:

private void button1_Click(object sender, EventArgs e)
{
    var loginUri = new Uri(@"http://localhost:5898/Account/Login");
    const string strLoginData = "Login=ojejq&Password=ojejqjejq&returnUrl=%2F";

    var cookie = GetAuthCookie(loginUri, strLoginData);
}

public CookieContainer GetAuthCookie(Uri loginUri, string data)
{
    var cookieJar = new CookieContainer();
    var request = (HttpWebRequest)WebRequest.Create(loginUri);
    request.Method = "POST";
    request.CookieContainer = cookieJar;
    request.ContentLength = data.Length;
    request.ContentType = "application/x-www-form-urlencoded";

    var myWriter = new StreamWriter(request.GetRequestStream());
    myWriter.Write(data);
    myWriter.Close();
    request.GetResponse();

    return cookieJar;
}

在我的ASP MVC应用程序中,我有一个/Account/Login POST控制器,甚至没有被上面的代码命中。我做错了什么?

编辑:我的asp mvc app中的两个登录操作:

[AllowAnonymous]
public ActionResult Login()
{...}

[HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginModel model, string returnUrl)
{...}

第二次更新:添加了登录模型

public class LoginModel
{
    [Required]
    [Display(Name = "Login", ResourceType = typeof(NameResources))]
    [StringLength(16, ErrorMessageResourceName = "LoginLengthError", ErrorMessageResourceType = typeof(NameResources), MinimumLength = 4)]
    public string Login { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password", ResourceType = typeof(NameResources))]
    [StringLength(32, ErrorMessageResourceName = "PasswordLengthError", ErrorMessageResourceType = typeof(NameResources), MinimumLength = 8)]
    public string Password { get; set; }
}

第三次更新:我忘了提及,在我的web.config中我设置了cookieless =“AutoDetect”选项。我不知道它是否有任何改变?

最终更新:首先,谢谢你们的时间,每个试图帮助我的人都会得到一个赞成。我发现问题不在代码中,而是在我的visual studio dev服务器中。它以某种方式重定向了我的button1 POST 请求,在此过程中丢失了数据,并将该请求更改为 GET 请求。我知道,werid,但代码还可以。谢谢你的时间。

1 个答案:

答案 0 :(得分:5)

我认为您应该尝试使用“UserName”而不是“Login”:

const string strLoginData = "UserName=ojejq&Password=ojejqjejq&returnUrl=%2F";

并试一试:

public CookieCollection GetAuthCookie(Uri loginUri, string data)
{
    var cookieJar = new CookieContainer();
    var request = (HttpWebRequest)WebRequest.Create(loginUri);
    request.Method = "POST";
    request.CookieContainer = cookieJar;
    request.ContentLength = data.Length;
    request.ContentType = "application/x-www-form-urlencoded";

    var myWriter = new StreamWriter(request.GetRequestStream());
    myWriter.Write(data);
    myWriter.Close();

    var webResponse = request.GetResponse() as HttpWebResponse;
    return webResponse.Cookies;
}